Joshua Leung Joshua Leung - 7 months ago 9
Javascript Question

Why there is a delay even though setTimeout is set to 0 delay?

console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
console.log('three');


The output is:
'one'
'three'
'two'

What happens behind the scene? Why the code produces this output?

Answer

setTimeout()don`t execute the given function "In X seconds after that you declare it", Behind the scenes, this method puts the given function in a stack that will be executed 'X second after that the code in the execution context have been executed, in this case, when the line 1 and the line 4 of your code has been executed"

An example

setTimeout(function() {
  console.log('four');
}, 10);
console.log('one');
setTimeout(function() {
  console.log('two');
}, 0);
console.log('three');

//Output: 'one', 'three', 'two', 'four'

Behind the scenes:

In the execution context

console.log('one');
console.log('three');

after the execution context setTimeout(fn, ms) sort in order of the second parameter, in milliseconds:

console.log('two');//0 ms after the execution context has been executed.
console.log('four'); //10ms after the execution context has been executed

EDIT: Have been search the link that in the next response explains graphically how works the javascript-browser queue, check it out!

Comments