I was perusing over a set of online javascript interview questions and noticed the following question:
function printing() {
console.log(1);
setTimeout(function() { console.log(2); }, 1);
setTimeout(function() { console.log(3); }, 2);
setTimeout(function() { console.log(4); }, 0);
console.log(5);
}
printing();
I expected the following code to print the following to the console: 1,5,4,3,2 My reason is that console.log(1) and console.log(2) is executed first while the setTimeout is sent to the eventloop where it waits for everything to finish first. Once 5 is printed, JS will look at the queue and 4,3,2 would push/pop in next.
However, on my Chrome browser I noticed 1,5,2,4,3 comes out instead.
I'm confused, but at the same time have a hunch that it may be due to the small increment of timeout delay that is causing the hiccup (perhaps a browser thing?). My reason for that is because I added two following zeroes to each number such that the delays become 100, 200, and 0.
Can anyone clarify what's going on under the hood, and any gotchas I should know about the delays?