http://ejohn.org/blog/how-javascript-timers-work/
At a fundamental level it's important to understand how JavaScript timers work. Often times they behave unintuitively because of the single thread which they are in. Let's start by examining the three functions to which we have access that can construct and manipulate timers.
-
var id = setTimeout(fn, delay);
- Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.
-
var id = setInterval(fn, delay);
- Similar to setTimeout
but continually calls the function (with a delay every time) until it is canceled.
-
clearInterval(id);
, clearTimeout(id);
- Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.
In order to understand how the timers work internally there's one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution. This is best demonstrated with a diagram, like in the following:
There's a lot of information in this figure to digest but understanding it completely will give you a better realization of how asynchronous JavaScript execution works. This diagram is one dimensional: vertically we have the (wall clock) time, in milliseconds. The blue boxes represent portions of JavaScript being executed. For example the first block of JavaScript executes for approximately 18ms, the mouse click block for approximately 11ms, and so on.
Since JavaScript can only ever execute one piece of code at a time (due to its single-threaded nature) each of these blocks of code are "blocking" the progress of other asynchronous events. This means that when an asynchronous event occurs (like a mouse click, a timer firing, or an XMLHttpRequest completing) it gets queued up to be executed later (how this queueing actually occurs surely varies from browser-to-browser, so consider this to be a simplification).
To start with, within the first block of JavaScript, two timers are initiated: a 10ms setTimeout
and a 10ms setInterval
. Due to where and when the timer was started it actually fires before we actually complete the first block of code. Note, however, that it does not execute immediately (it is incapable of doing that, because of the threading). Instead that delayed function is queued in order to be executed at the next available moment.
Additionally, within this first JavaScript block we see a mouse click occur. The JavaScript callbacks associated with this asynchronous event (we never know when a user may perform an action, thus it's consider to be asynchronous) are unable to be executed immediately thus, like the initial timer, it is queued to be executed later.
After the initial block of JavaScript finishes executing the browser immediately asks the question: What is waiting to be executed? In this case both a mouse click handler and a timer callback are waiting. The browser then picks one (the mouse click callback) and executes it immediately. The timer will wait until the next possible time, in order to execute.
Note that while mouse click handler is executing the first interval callback executes. As with the timer its handler is queued for later execution. However, note that when the interval is fired again (when the timer handler is executing) this time that handler execution is dropped. If you were to queue up all interval callbacks when a large block of code is executing the result would be a bunch of intervals executing with no delay between them, upon completion. Instead browsers tend to simply wait until no more interval handlers are queued (for the interval in question) before queuing more.
We can, in fact, see that this is the case when a third interval callback fires while the interval, itself, is executing. This shows us an important fact: Intervals don't care about what is currently executing, they will queue indiscriminately, even if it means that the time between callbacks will be sacrificed.
Finally, after the second interval callback is finished executing, we can see that there's nothing left for the JavaScript engine to execute. This means that the browser now waits for a new asynchronous event to occur. We get this at the 50ms mark when the interval fires again. This time, however, there is nothing blocking its execution, so it fires immediately.
Let's take a look at an example to better illustrate the differences between setTimeout
andsetInterval
.
setTimeout(function(){
/* Some long block of code... */
setTimeout(arguments.callee, 10);
}, 10);
setInterval(function(){
/* Some long block of code... */
}, 10);
These two pieces of code may appear to be functionally equivalent, at first glance, but they are not. Notably the setTimeout
code will always have at least a 10ms delay after the previous callback execution (it may end up being more, but never less) whereas thesetInterval
will attempt to execute a callback every 10ms regardless of when the last callback was executed.
There's a lot that we've learned here, let's recap:
- JavaScript engines only have a single thread, forcing asynchronous events to queue waiting for execution.
-
setTimeout
and setInterval
are fundamentally different in how they execute asynchronous code.
- If a timer is blocked from immediately executing it will be delayed until the next possible point of execution (which will be longer than the desired delay).
- Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).
All of this is incredibly important knowledge to build off of. Knowing how a JavaScript engine works, especially with the large number of asynchronous events that typically occur, makes for a great foundation when building an advanced piece of application code.
- 大小: 328.2 KB
分享到:
相关推荐
由 John Resig 的 How JavaScript Timers Work 可以知道,现有的 JavaScript 引擎是单线程处理任务的。它把任务放到队列中,不会同步去执行,必须在完成一个任务后才开始另外一个任务。
A Stock Exchange simulator to show how timers and randon number generators work together. A cool simulation for anyone who might think about playing the stocks and spending money and get a general ...
Title: Beginning ...Beginning JavaScript, 5th Edition shows you how to work effectively with JavaScript frameworks, functions, and modern browsers, and teaches more effective coding practices using ...
commonj.work.Work.java commonj.work.WorkCompletedException.java commonj.work.WorkEvent.java commonj.work.WorkException.java commonj.work.WorkItem.java commonj.work.WorkListener.java commonj.work....
c# Timers简单的定时应用 对入门学的有用
jquery.timers-1.2.js 定时器插件
Throughout this part we will, among other things, learn how to test code that depends on browser API’s, timers, event handlers, DOM manipulation, and asynchronous server requests (i.e., “Ajax”)....
Test existing JavaScript code using JSLint and understand how to better optimize JavaScript code Create your own build system for JavaScript projects using Node.js and GulpJS Get to know best ...
jquery资源 ,jquery.timers定时器资源
jQuery Timers 是一个用来封装 setTimeout 和 setInterval 方法的 jQuery 定时器插件。
Timers 有研究或探讨或开源的请加群:37424970 或联系本人MSN或邮箱:zhuseahui@yahoo.com.cn
using bios timers in IBM pc
Learn MFC to know how the messages work and timer will give very swift result
jQuery timers定时器简单易懂。。 直接调用,时间设置可以自己修改
commonj.timers.CancelTimerListener.class commonj.timers.StopTimerListener.class commonj.timers.Timer.class commonj.timers.TimerListener.class commonj.timers.TimerManager.class commonj.work....
jquery_timers实现带暂停功能的全屏相册实例源码,供大家一起参考学习。
TMS320VC5509_DSP_Timers_Reference_Guide
该文件 使用Spring实现了一个定时器 适用于初学者开发使用
Addresses the basics: modules, buffers, events, and timers Explores streams, file systems, networking, and automated unit testing Goes beyond the basics, and shares techniques and tools for debugging,...
本文实例讲述了C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析,分享给大家供大家参考。具体分析如下: 在.NET Framework里面提供了三种Timer ① System.Windows.Forms.Timer ② System.Timers.Timer ③...