Search code examples
javascriptsettimeoutevent-loop

Why is the `setTimeout` callback called after function execution, even if the delay is 0 ms?


setTimeout(function(){
  console.log("m");
}, 0);
console.log("s");

Why does this code print "s" before "m", even if the setTimeout callback is supposed to wait for 0 ms?


Solution

  • When you create a promise, or call an async function, or set a timeout for 0 milliseconds, the function is immediately queued into the Javascript event loop. Essentially, the function is added to a queue of functions to call, and once the javascript interpreter has nothing to do it'll start calling those functions. So, when you set a timeout for 0 milliseconds, it queues the console.log("m"), then calls the console.log("s"), then it has nothing to do so it finishes the queued console.log("m"), which is why it's out of order.