Given the following example:
for(var i=1;i<=5;i++){
setTimeout(function timer(){
console.log(i)
}, 0);
console.log(i);
}
This prints out:
1
2
3
4
5
6
6
6
6
6
setTimeout
does not get executed immediately but rather after the loop has ended, despite the fact that console.log
got executed immediately with each iteration within the loop.
I did a little research into this, but the most information I could find stated that although the anonymous function within setTimeout
was added to the task queue that JavaScript executes, it doesn't necessarily get called immediately.
My question is that how does the browser determine which functions get priority in terms of execution?