In the code below, the delay for 2 is 0secs, So why does it outputs 2 after 3 and not before it?
(function() {
console.log(1);
setTimeout(function(){console.log(2)}, 0);
console.log(3);
})();
It will execute in the following matter:
1 3 2
setTimeout is implemented in a way it's meant to execute after a minimum given delay, and once the browser's thread is free to execute it. so, for an example, if you specify a value of 0 for the delay parameter and you think it will execute "immediately", it won't. it will, more accurately, run in the next event cycle (which is part of the event loop - concurrency model which is responsible for executing the code).
So, the printing of 1 and 3 will actually by pushed to the call stack and will execute immediately where as the setTimeout call back function will only be available to be pulled from the event queue to be picked in the next event loop tick.
Please read reason for delays longer then specified - https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified
More about the JS event loop - https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
setTimeout() doesn't delay everything called after it; it only delays the function within. So it starts a timer for console.log(2), continues with the remaining code, console.log(3), and then runs the timeout function when the timer runs out.
This selfinvoked anonymous function declaration
function (function() {
console.log(1);
setTimeout(function(){console.log(2)}, 0);
console.log(3);
})();
is the same as if you've written
console.log(1);
setTimeout( console.log, 0, 2);
console.log(3);
and the order of logs will be the same - be it wrapped or unwrapped in an anonymous timed function - because it will be resolved during runtime, whereas the setTimeout declaration is a program, and will have to wait until the program starts execution.
And it/this will be after the JITC has finished compiling your code.