setTimeout(func,0) not called immediately.
It just mimics an asynchronous function with a callback.
function asyncFunc(callback) { console.log("step1"); setTimeout(callback,0); console.log("step2"); } asyncFunc(function() {console.log("async step")});
https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout
The code executed by setTimeout () is run in a separate execution context of the function with which it was called
Thus, it starts in a separate execution context, but before executing it, javascript must complete the current execution due to the fact that javascript runs on a single thread.
It doesnβt matter how much time is in the current execution, because it MUST end before performing another task.
if you have an infinite loop to the end of the task, for example, your callback will never be called.
source share