console.log("start");
setTimeout(function cb() {
console.log("callback");
}, 5000);
console.log("end");
lets say during execution of this code, setTimeout
registers this callback into web APIs, then there is 10^6 lines of code to be executed that takes 10 seconds; but out timeout takes 5 seconds to execute; but after 5 second main thread is still used by our program so we can’t execute this callback; after another 5 second, when main thread is freed, this callback is executed
so setTimeout
for 5 sec does not mean that after 5 sec it will execute, it can execute at least after 5 sec.
console.log("start");
setTimeout(function cb() {
console.log("callback");
}, 0);
console.log("end");
OUTPUT:
start
end
callback