MENU
Macrotasks and Microtasks
Below, setTimeout(...,0) causes the callback to run in the next round of macrotask execution, only after all tasks in the microtask queue have ended.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
(function test() {setTimeout(function() {console.log(6)}, 9); // queued into the macrotask queue as another tasksetTimeout(function() {console.log(5)}, 0); // the argument 0 is optional here
new Promise(function executor(resolve) {
console.log(1);
for( var i=0 ; i<10000000000; i++ )
i == 9999 && resolve(); // a long pause!
console.log(2);}).then(function() { // first queued into the microtask queue
console.log(4);
});
console.log(3);})(); // 1 2 3 4 5 6
</script></body><html>
Note that the code enclosed by <script> represents a task for the macrotask queue. Additionally, a callback for a DOM event such a 'click', setTimeout(), etc. queue a task to the macrotask queue. This explains why, above, the callbacks within setTimeout() are executed only after all the jobs queued by a Promise into the microtask queue end, in the next round of macrotask execution.