Reputation: 619
I'm a bit confused with timers in Javascript. I've been playing around with timers.
I'm confused with how the queuing process in asychronous events happen. I have read about the article about how asynchronous events are queud. But i find it hard to wrap my head around the queuing process.
Here's the code:
http://jsbin.com/iwahuf/2/edit
In the code that i have posted would the timers be queud in sequence. Wouldn't the timers in the event queue be executed FIFO (First In, First Out).
Here's what i have in mind in the event queue.
In my opinion, since the first timer has been the first to be registered in the Event queue, it will be the first to be executed and only after 500ms will the second timer be executed and so on.
Please enlighten me on this matter. I'm a litte confused. I think my understanding of the queuing process is not quite right.
Thanks in advance.
Upvotes: 0
Views: 161
Reputation: 382092
Registering a timer doesn't stop your code. You're registering all timers at the same time, the scheduler will try to execute them N ms after the time of registration.
This means that
If you want to queue your timers, either you chain them (by making each of them call the next one) or (much lighter and simpler if the tasks are short) you compute yourself the times :
var time = 0;
setTimeout(function(){
console.log("First Timer");
}, time += 500);
setTimeout(function(){
console.log("Second Timer");
}, time += 600);
console.log("Executed immediately");
setTimeout(function(){
console.log("Third Timer");
}, time += 300);
setTimeout(function(){
console.log("Fourth Timer");
}, time += 400);
In this somewhat related answer I give an implementation of a simple queue.
Upvotes: 2
Reputation: 1254
When a timeout is set in Javascript, it does not halt execution of the following code. instead, it delays the execution of the function set to run on timeout. TO acheive your expected results, your code would need to look like this:
setTimeout(function(){
console.log("First Timer");
setTimeout(function(){
console.log("Second Timer");
setTimeout(function(){
console.log("Third Timer");
setTimeout(function(){
console.log("Fourth Timer");
}, 400);
}, 300);
}, 600);
}, 500);
console.log("Executed immediately");
Hope this helps!
Upvotes: 1
Reputation: 339776
No, timers are not first-in-first out.
It's not the timers themselves that are put in the event queue - when timers expire they result in a "timer elapsed" event being added to the FIFO event queue as they expire.
How timer objects actually detect that they've expired and create those events is out of scope, and probably implementation dependent.
Upvotes: 1