4 ms·
1) setTimeout is a Browser/Node API, not a Javascript method 2) Functions that are being returned from the Browser API are pushed to a special waiting area (ca
by dentemple 8y ago
1) setTimeout is a Browser/Node API, not a Javascript method
2) Functions that are being returned from the Browser API are pushed to a special waiting area (called the "Callback queue"), not to the immediate Call Stack
3) Functions are only taken from the Callback queue when both the Call Stack and the other higher priority queues (like the "Job" Queue) are empty.
When setTimeout is invoked, the Javascript engine sends func and 0 as arguments to the API, then moves on. The engine doesn't get blocked by setTimeout, nor does it wait to see the end result. Javascript's job is done here, and so it just moves on to the rest of the code.
When the API receives setTimeout's arguments, it executes the Timer(?) method, passing to it an argument of 0 seconds. This resolves immediately.
However, the API isn't allowed to send functions straight back into the Call Stack. Functions are forced into an intervening waiting area called the Callback Queue. (In the case of promises, there's also a higher priority queue that functions can be sent to instead: the "Job" or "Micro-task" Queue).
Javascript's event loop will only pull functions from the Callback Queue when 1) the main thread of execution has finished all of its synchronous code, 2) the Call Stack is empty, and 3) no higher priority queues have functions left to be pulled either.
Therefore, in the case of "setTimeout(func, 0)", func can be forced to wait a very long time, indeed. If the intervening synchronous code takes 10,000 ms to run, the func from setTimeout(func, 0) will, at a minimum, run at the 10,000 ms point.
However, back in the days of "callback hell", this was often the reason why you'd do a "setTimeout(func, 0)" or two in the first place: to manipulate the order in which certain functions were run by the thread of execution.
Since, literally, what it does it knock a function out of the normal order of events and places it into a lower priority queue.