Reputation: 11
See the below code
vat t = setTimeout(x, 1000);
vat t1 = setTimeout(y, 1100);
var t2 = setTimoue(z, 4000);
The order of execution is t, t1 and t2. So, t is executed after 1s. Till here is fine. Then is t1 executed after 100ms(1100 - 1000) or is it executed 1100ms after t is executed?
Upvotes: 0
Views: 82
Reputation: 88
Above is the correct answer, although I would encourage you, going forward, when possible, to go open up the JavaScript console in your browser and figure it out yourself. console.log(Date.now()) in your code and test it. When I first got into coding, I would always turn to pros for simple questions (out of habit), but in my experience, being successful in coding often means knowing HOW to get the answer, as opposed to just knowing WHAT the answer is.
Additionally, I would argue you're much more likely to remember the answer if you identified it yourself instead of someone just telling you.
Good luck!
Upvotes: 1
Reputation: 1098
JavaScript is single-threaded. If some block of code uses execution thread, no other code can be executed. This means your setTimeout() call must wait until main execution finishes. [from here]setTimeout behaviour with blocking code
Upvotes: -1
Reputation: 7413
If you want to control the order of execution I really think you should sequence the timeouts.
var t = setTimeout(x, 1000);
function x(){
setTimeout(y, 100);
}
function y(){
setTimeout(z, 2900);
}
In any case I'm not sure you should be doing any of this in the first place. If you want to call one function after another just use the .call or .apply. take a look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
Upvotes: 0
Reputation: 4738
t1 will be executed 100ms after t was executed.
But actually, if the page is busy, setTimeout may be fired later so that it can less or greater than 100ms.
Upvotes: 1