Thanks a lot John Resig (he is creator of Jquery framework). I read his blog that mentioned about “Javascrip Timers” and i already took a long time to absolutely understanding this concepts.
Before i go more details, we have some important concepts need to be explored.
- Timers delay is not guaranteed. The timers in this blog mention are setTimeout(fn, delay) and setInterval(fn, delay).
So if you still confusing, please have a look this picture below:
If you look at this picture it is have three columns:
- First column: we have the wall lock time in miliseconds (0, 10, 20, 30, 40, 50) and what’s waiting in event queue.
- Third column: Represent where and when the timer and mouse click was started.
Let’s go more details what’s happen behind the scenes:
Additionally, within this first block we see a mouse click occur and it have to queue. After the first block finished executing the browser immediately asks the question. What is waiting to be executed? So in this case a mouse click handler and timer are waiting then the browser picks one(the mouse click callback).
The browser pick the mouse click callback because of FIFO, mouse click callback was added to event queue before the timer. And the timer will wait until the next possible time.
Then, the second block represent the mouse click callback is executing. In this time, we see the first interval callback executes and it is queued for execution later.
Then, when the interval is fired again in this time the timer is executing. This time that handler execution is dropped.
Now, we have 2 interval callbacks are waiting, thus the result would be a bunch of intervals executing with no delay between them. Instead browsers just simply wait until no more interval handlers are queued before queuing more.
This show us an inportant fact: The interval don’t care what is currently executing, they will queue indiscriminately, even if it means that the time between callbacks will be sacrificed.
Behind the scene, right after the setTimeout and setInterval function is executed, the browser places setTimeout’s callback and setInterval’s callback function into an Event Table. When the event happen, the event table will simply move the function over to the Event Queue.
In this situation, The Event Table will move the interval callback to Event Queue every 10ms. And whenever the browser asking what is waiting to be executed? The browser will pick the first interval callback and browser will ask and ask again, thus the second interval callback will be executed immediately.
- If a timer is blocked from immediately executing it will be delayed until the next possible point of execution.
- Intervals may execute back-to-back with no delay if they take long enough to execute.