Reputation:
function a() {
for(i=0;i<4;i++){
b(i);
}
}
function b(j){
setTimeout(function(){
console.log(j);
},3000);
}
a();
Can someone please explain to me how the above code is executed in terms of the event queue and execution contexts?
From my understanding of JS, I know that the event queue is not processed until all the code in the JS file is finished. So first a is invoked in the global scope. Then inside of function a(), a for loop is present which invokes b four times. So my question is in every invocation of function b, a timer event will be placed on the event queue. Does this timer event wait for three seconds and then callback the function that was passed to the setTimeout method? Or does it just place a timer event on the queue, then go back to function a, invoke b again, and this would place another timer event in the queue. So basically until the for loop is not finished invoking b four times, the timer event for 3 seconds will not start. But when it is done invoking b four times,then the first timer event placed on the queue starts and calls back to the function passed in to the parameter of setTimeout and because of closures it knows that j = 0. Then this happens for the next 3 events in the queue? So basically the events are not processed until all the code in the JS file is finished where in this case it is the invocation of function b three times?
If my understanding is completely wrong, please feel free to explain this code above in your own terms without reading my explanation haha!
Upvotes: 2
Views: 374
Reputation: 943547
Does this timer event wait for three seconds and then callback the function that was passed to the setTimeout method? Or does it just place a timer event on the queue, then go back to function a, invoke b again, and this would place another timer event in the queue.
The latter.
Leaving aside the fact that it won't take 3 seconds to call b
4 times, JavaScript will never pause in the middle of a function to run another function because an event has fired. It would be too busy running a()
to look to see if there are any timeout events waiting to run.
Upvotes: 2