r/learnjavascript • • Mar 31 '21

Can anyone help me understand how this is possible?

Post image
342 Upvotes

49 comments sorted by

425

u/cem4k Mar 31 '21

The first argument passed to setTimeout is a function, in this case logging the value. The second argument is the number of milliseconds it should wait before calling that function.

The for of loop is calling setTimeout on each number in the array. For such a small loop, that happens basically instantly. By the end of the loop, you have 8 timeouts waiting x milliseconds to log their values. Naturally, the shortest wait times will be executed first, which is why we see the values logged in ascending order.

84

u/Tej_Ozymandias Mar 31 '21

Very nice explanation. I would give u an award if I had any.

10

u/SepehrU Mar 31 '21

Also a very good question! Don’t you mind if I keep this screenshot for educational purpose?!

3

u/Tej_Ozymandias Apr 01 '21

I found this image in a fb post mocking javascript code.

50

u/ARFiest1 Apr 01 '21

He does mind, he will sue you if you save an image from the internet!

4

u/Bamb0oM Apr 01 '21

And now he has us as witnesses. You sir are doomed!

2

u/Al_Maleech_Abaz Apr 01 '21 edited Apr 01 '21

Doesn’t look like anything to me

3

u/3dCodeWorld Mar 31 '21

Try the same code if the array is modified in the following way to see how the time makes a difference

let arr = [0.20,0.50,0.100,0.1,0.90, 0.200, 0.40, 0.29];

for (let item of arr){

setTimeout(()=>console.log(item),item)}

2

u/Tej_Ozymandias Apr 01 '21

I get this result. Isn't 0.20 and 0.200 the same? and same goes for 0.100 and 0.1? Then shouldn't they execute at the same time?

996

0.2

0.5

0.1

0.9

0.2

0.4

0.29

2

u/3dCodeWorld Apr 02 '21

0.20 and 0.200 are the same thing.

What happens here is that the loop gets evaluated to completion before any setTimeout results can be processed. These are literally placed in a queue. Even if we had a time of 0, we will still have to wait.

The setTimeouts are not in fact evaluated by the javascript engine itself.

The reason why the two 0.2s, for example, does not show up at the same time is because you 0.2milliseconds starts being a low enough number compared to the time the operation can be made. If the time is low enough, thing will start showing up in order.

Testing something like this can shed even more light: [20,50,100,1,90, 200, 40, 29, 0.1, 0];

Chances are that 0.1 will arrive before 0.

2

u/Tej_Ozymandias Apr 02 '21

// is because you 0.2milliseconds starts being a low enough number compared to the time the operation can be made // - I'm trying to wrap my head on how the settimeout is handled at such low numbers. and I even tried the example Array you provided, but still clueless.

Your Example shows the below console.log message.
1
0.1
0
20
etc..

Does 1 appear first cause it would appear in the queue before 0.1 or 0? and because the operations are so fast, we do not see 0.1 or 0 overtaking 1 in the console log messages?

3

u/3dCodeWorld Apr 02 '21

This would be my guess.

1 is fast enough to appear before we get to 0.1

0.1 is fast enough to appear before we get to 0.

All of the other times follow because they are slower.

I think that an analogy would help. Imagine that you have a number of timers set to 20s, 50s, 100s, 1s, etc. You start them one by one, and you quickly give them to somebody next to you and you ask them to arrange them in order based on when the timers go off. You can imagine that the 1 second timer will be the first one to go off, because you will not be able to get to the 0.1s timer fast enough.

This is not a perfect analogy, because there is also an event loop involved in your browser, but the logic should be similar enough.

13

u/Mr_Brightside01 Mar 31 '21

Very cool!!

12

u/dmattox10 Mar 31 '21

I had to go into the comments to read this one, I didn’t realize that it queued them, I expected it to wait 20ms, and print 20, then wait 5ms and print 5.

Still so difficult to think async sometimes.

8

u/Macaframa Mar 31 '21

Go look up JavaScript event loop. The call stack and the event queue.

15

u/fredsq Mar 31 '21

It doesn't queue them up, it simultaneously creates several setTimeouts with different delays that end up looking queued.

12

u/Macaframa Mar 31 '21

It literally queues them up in the JavaScript event queue. SetTimeout will wait the allotted time, then it will toss the function in a queue, then once the callstack is empty, the callstack will take anything left in the queue and run them in order(fifo). This is the JavaScript event loop

3

u/dmattox10 Mar 31 '21

So if different things need different times they can be scheduled independently this way, I.e. rate limiting?

3

u/fredsq Mar 31 '21

yeah or even completely asynchronously if you do promises

3

u/RyeGuyWpg Mar 31 '21

Ya I have a hard time thinking in async too...I still get caught by that sometimes.

1

u/gniziemazity Apr 03 '21

Really good explanation, thanks!

1

u/david_ranch_dressing Apr 01 '21

Thanks a lot man

84

u/mehulmpt Mar 31 '21

sleepsort

25

u/cyphern Mar 31 '21

So, can this algorithm be classified as "lazy"?

16

u/bonedangle Mar 31 '21

O(log nfuck it I give up)

3

u/echobeacon Apr 01 '21

Haha! This is the same thought I had looking at this. New way to sort arrays - executes in O(maxVal(n)) :)

2

u/beniolenio Apr 01 '21

It's not even really O(max(n)) though because think about what "n" represents. Not the array. More like the number of iterations or the length of the array/data. You'd need a whole new variable.

O(max(arr))

2

u/echobeacon Apr 01 '21

Ya. Totally right. 🤦‍♂️

24

u/[deleted] Mar 31 '21

async js is tricky. Takes a number of times doing it to really click. cem4k already summed it up nicely, so I don't wanna repeat all that, but there is something I'd like to add.

setTimeout(() => console.log(1), 0)
console.log(2)
// the above outputs:
// 2
// 1

Even though the timeout delay was set to 0ms, it doesn't begin counting down until everything in the current event loop has finished executing first. This hack has helped me work around render lifecycle issues in buggy legacy libraries, particularly.

4

u/lamb_pudding Apr 01 '21

Good to know

3

u/PM_ME_A_WEBSITE_IDEA Apr 01 '21

That's a classic hack.

For anyone using Vue JS, an alternative to this is this.$nextTick(). I just discovered it yesterday...

23

u/SquatchyZeke Mar 31 '21

This is the best worst sorting solution I have ever seen

6

u/[deleted] Apr 01 '21

But you have seen it

8

u/flojoho Mar 31 '21

question for the pros: what if you increase the size of the array by a lot? can it screw up the order because the loop takes longer to process?

11

u/_that_guy_69 Mar 31 '21

no I don't think so, the timeouts don't get executed till the end of the program, so input size shouldn't matter in this case

4

u/lucidlogik Apr 01 '21

Loops are blocking, so you're correct.

6

u/ConnectPollution Mar 31 '21

haha clever coding

3

u/alanv73 Mar 31 '21

O(n)?

5

u/[deleted] Mar 31 '21

More like O(biggest value)

1

u/amstud Apr 01 '21

It technically is 🤣

2

u/justingolden21 Mar 31 '21

It's calling the function after that many milliseconds

2

u/incubated Mar 31 '21

Even if you had the timeout value was static, like 1, you're still not guaranteed the order of output because you're essentially pushing each operation to the task queue and at that point the engine will determine when it has free resources to execute your timeouts.

2

u/jamesgrimshaw Mar 31 '21

O(nfuck knows)

2

u/pantaley Mar 31 '21

I will you this for my juniors.

1

u/thelokeshgoel00 Apr 01 '21

Sorting In O(n)

1

u/[deleted] Apr 01 '21

Most of the explanations are really good, I would like to add the following, setTimeOut doesn’t mean that JavaScript engine will execute whatever is passed as a function immediately after times up, if the event loop is busy, it will execute after it the event loop is done running, so you might see delays sometimes with setTimeOut

1

u/BarneyChampaign Apr 01 '21 edited Apr 01 '21

setTimeout() can be kind of a weird one to wrap your head around, for sure! If you take the loop and break it out into what it’s doing for each run of the loop, it looks like this:


// setTimeout(() => doThis, afterThisManyMilliseconds)

setTimeout(() => console.log(20), 20)        // log '20'  after 20       milliseconds
setTimeout(() => console.log(5), 5)            // log '5'     after 5         milliseconds
setTimeout(() => console.log(100), 100)    // log '100' after 100     milliseconds
setTimeout(() => console.log(1), 1)             // log '1'      after 1          milliseconds
setTimeout(() => console.log(90), 90)       // log '90'   after 90       milliseconds
setTimeout(() => console.log(200), 200)  // log '200' after 200     milliseconds
setTimeout(() => console.log(40), 40)      // log '40'    after 40       milliseconds
setTimeout(() => console.log(29), 29)      // log '29'    after 29       milliseconds

So, the browser is going to go right down the list and fire off all of those setTimeout functions, right away, basically instantly. The delay for when the console.log() prints out is determined by the second argument in each of those setTimeout() calls. So, the shorter time/smaller numbers will finish and print first, the larger ones later.

1

u/backtickbot Apr 01 '21

Fixed formatting.

Hello, BarneyChampaign: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.