Reputation:
function waitForThreeSeconds(){
setTimeOut(function(){
console.log('Time done');
},3000);
}
waitForThreeSeconds();
console.log('finished execution');
In the code above, when the waitForThreeSeconds function is invoked an event is placed on the event queue for the setTimeout method. My question is when the waitForThreeSeconds function is invoked, will the three second timer in the function expression passed into setTimeout start immediately when the JS engine encounters the setTimeout method? Or will an event be placed on the event queue. Then after console.log("finished execution') line of code is run in the global execution context (which means everything is done executing in the JS file), then the three second timer will start and the callback function passed to setTimeout will run.
I am not sure when the timer in the setTimeout function actually starts. Would it start exactly when the JS engine encounters the setTimeout method or will the three second timer start when the JS engine goes to the event queue to process the event placed by the setTimeout method?
Upvotes: 0
Views: 637
Reputation: 11
setTimeout
is added to the mission of the end of the "task queue":
function waitForThreeSeconds(){
setTimeout(function(){
console.log('Time done');
},0);} waitForThreeSeconds();console.log('finished execution');
Upvotes: 0
Reputation: 790
So as we should already know, JavaScript is not a multi-threaded language, and is therefore a single-threaded language, although you can add events, terminate events, and even invoke events.
When creating an event, you add the event token on top of the queue, therefore it will be the last event to be recognized.
In your code, here is what happens:
waitForThreeSeconds()
:
calls wait for three seconds
calls setTimeout([...], 3000)
:
adds event as last token in event queue
at this point your event queue should look like:
[this.event, that.event, all.otherEvents, ECMA.TimeStamp(3000)
]
The TimeStamp(3000) is the way we will represent the timer...
So every 1/1000 of a second (abstractly) the JS Engine will check the event queue for events which have been invoked. When it recognizes that TimeStamp(3000)
has been invoked (after 3000 milliseconds) it will now invoke the callback function.
The weird part is that when you say setTimeout([...], 3000)
, the JS engine adds the callback to the event queue, and moves on from there. It will not wait the 3 seconds to move on to the next line of code.
So as soon as you call setTimeout()
, it will start the timer. So if it takes 2000 milliseconds to run the rest of your code, then 1000 milliseconds later your callback will be called... =)
Upvotes: 0