3

I am executing Part1, Part2, Part3 and Part4 separately (in different files).

I estranged about the execution of my code. Why Part1 output is like A B But I am expecting B A. Like Part4. Could you please give the exact reason about same.

//Part1
setTimeout(function(){ console.log('A') }, 1);
setTimeout(function(){ console.log('B') }, 0);
Out Put of console: A B

//Part2
setTimeout(function(){ console.log('A') }, 4);
setTimeout(function(){ console.log('B') }, 3);
Out Put of console: B A

//Part3
setTimeout(function(){ console.log('A') }, 3);
setTimeout(function(){ console.log('B') }, 4); 
Out Put of console: A B

//Part4
setTimeout(function(){ console.log('A') }, 2000);
setTimeout(function(){ console.log('B') }, 0);
Out Put of console: B A
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42
Ankit Pandey
  • 608
  • 4
  • 17

2 Answers2

4

The setTimeout function has its delay value clamped, which means the 0 is ignored and set to a minimum value (usually 4ms or 10ms depending on the browser). Also, if the tab is inactive, the timeout may be delayed even further.

But when you give the setTimeout value 1, it will call it after 1ms. Javascript will not ignore value 1 in setTimeout but it can ignore 0.

postMessage is best way to use in place of setTimeout to 0.

One more thing when you are using this little difference of time (one value is zero), then sometime it execute the function according to the order of them in code.

For check you can put your setTimeout value 0 on before the setTimeout value 1 function. It will run setTimeout value 0 first then setTimeout value 1.

Manoj Lodhi
  • 978
  • 4
  • 10
  • 1
    The 4ms clamp is detailed here https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Reasons_for_delays_longer_than_specified – scipilot Dec 21 '16 at 12:25
0

The reason is that javascript executes statements in the order they are written. For example, in your code, you have written:

setTimeout(function(){ console.log('A') }, 1);
setTimeout(function(){ console.log('B') }, 0);

This literally means: Wait 1 milllisecond, write "A" to the console, then write "B" to the console. You must place the statements in the order you need them to be executed in.

Wais Kamal
  • 5,858
  • 2
  • 17
  • 36