Abhishek Sharma
Abhishek Sharma

Reputation: 3280

Nested settimeout with same time prints random

I know in javascript that this code will always print

setTimeout(function(){
  console.log('a');
}, 1000)

setTimeout(function(){
  console.log('c');
}, 1000)

setTimeout(function(){
  console.log('b');
}, 1000)

a
c
b

And I can rearrange set timeout to get output i want on the basis of lines and those items will be in queue ready to be executed. But I don't understand why this code print values randomly. Shouldn't this also be based on how javascript pushes code to queue and print same value everytime instead of random print.

setTimeout(function(){
  setTimeout(function(){
    console.log('a');
  }, 500)
}, 500)

setTimeout(function(){
  setTimeout(function(){
    console.log('b');
    }, 800)
}, 200)

setTimeout(function(){
  setTimeout(function(){
  console.log('c');
  }, 400);
}, 600);

Upvotes: 2

Views: 118

Answers (2)

Paul
Paul

Reputation: 141839

You're understanding of the first case seems fine. After one second, they are all added to the event queued in order, so they execute in that order, but think about what order the events are queued in your second example, while noting that timeouts and intervals are not exact.

A timeout of 200 means at least 200 milliseconds, not exactly 200 milliseconds. So, suppose your timeout of 200 executes after 203 milliseconds, then immediately queues b to execute 800 milliseconds later. b will be queued to execute after at least 1003 milliseconds from when the first timeouts were started. The first timeout for a could execute after 502 milliseconds, and the first timeout for c could execute after 601 milliseconds. Then you would get the output: c a b. If the first timeout had happened immediately after 200 milliseconds instead of after 203 you would've seen: b c a.

Upvotes: 3

cybersam
cybersam

Reputation: 66977

As the documentation for setTimeout states:

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

Upvotes: 2

Related Questions