Repost this articleArticleThe reason is that it explains the difference between setTimeout and setinterval, for this article, blog garden has a friend translated, URL: http://www.cnblogs.com/rainman/archive/2008/12/26/1363321.html
Translation content:
How JavaScript timers work
At the basic level, it is very important to understand how the Javascript timer works. Timer execution is often different from our intuitive imagination, because the JavaScript engine is single-threaded. Let's first understand how the three functions under the timer control the timer.
VaR id = setTimeout (FN, delay );
-Initialize a timer and run it after the specified interval. This function returns a unique identifier ID (number type), which can be used to cancel the timer.
VaR id = setinterval (FN, delay );
-It is similar to setTimeout, But it continuously calls a function (the interval is the delay parameter) until it is canceled.
Clearinterval (ID );
,Cleartimeout (ID );
-Use the timer ID (returned values of setTimeout and setinterval) to cancel the occurrence of the timer callback.
To understand the internal execution principle of a timer, there is an important concept that needs to be discussed: the timer delay (Delay) cannot be guaranteed. Because all JavascriptCodeIt is executed in a thread. All asynchronous events (such as mouse clicks and timers) are executed only when they have the chance of execution. Use a good chart to describe:
(Click to view the chart)
There is a lot of information to understand in this chart. If you fully understand them, you will have a good understanding of how the JavaScript engine implements asynchronous events. This is a one-dimensional icon: the vertical direction indicates the time, and the blue block indicates the JavaScript code execution block. For example, the first JavaScript code execution block takes about 18 ms, and the code execution block triggered by clicking the mouse takes 11 ms.
Because the JavaScript engine only executes one piece of code at a time (this is due to the nature of a single JavaScript thread), every JavaScript code execution block will "Block" the execution of other asynchronous events. This means that when an asynchronous event occurs (for example, a mouse click, a timer is triggered, or an Ajax asynchronous request, the callback functions of these events will be placed at the end of the execution Queue (in fact, the queuing method varies with the browser, so this is just a simplified process );
Starting from the first javascript execution block, two timers are initialized in the first execution block: A 10 msSetTimeout ()
And a 10 msSetinterval ()
. The timer is triggered before the execution of the first code block, depending on when and where the timer is initialized (the timer starts timing after initialization. However, the function bound to the timer will not be executed immediately (the reason for not being executed immediately is that JavaScript is single-threaded ). In fact, the delayed functions will be placed at the end of the execution queue in sequence, waiting for the next appropriate time for execution.
In addition, we can see a "mouse click" event in the first javascript execution block. A JavaScript callback function is bound to this asynchronous event (we never know when the user will execute this (click) event, so we think it is asynchronous ), this function will not be executed immediately. Like the timer above, it will be placed at the end of the execution queue, waiting for the next execution to be appropriate.
After the first javascript execution block is executed, the browser immediately asks the following question: which function (statement) is waiting to be executed? At this time, a "mouse click event processing function" and a "timer callback function" are waiting for execution. The browser selects a (actually selects the "processing function of the mouse click event", because the figure shows that it is the first team) to execute immediately. The "timer callback function" will wait for the next appropriate time for execution.
Note: When the "mouse click event processing function" is executed,Setinterval
The callback function is triggered for the first time. AndSetTimeout
The callback function is the same as the callback function. However, pay attention to this: WhenSetinterva
L when the callback function is triggered for the second time (at this timeSetTimeout
The function is still being executed)SetTimeout
The first trigger will be discarded. When a long code block is executedSetinterval
The callback functions are all placed behind the execution queue. After the code block is executed, the result is a large string of setinterval callback functions waiting for execution, and there is no interval between these functions until they are all completed. Therefore, browsers tendInterval
In the queue, the next processing function is placed at the end of the Team (this is due to the gap problem ).
We can find that when the thirdSetinterval
When the callback function is triggered, the previous setinterval callback function is still being executed. This illustrates a very important fact:Setinterval
All blocked functions are routed to the end of the queue without considering what is being executed. This means that the time interval between the two setinterval callback functions will be sacrificed (reduced ).
Finally, when the secondSetinterval
After the callback function is executed, we can see that there is noProgramWait until the JavaScript engine is executed. This means that the browser is waiting for a new asynchronous event. At 50 ms, a newSetinterval
The callback function is triggered again. At this time, no execution block blocks its execution. So it will be executed immediately.
Let's use an example to illustrateSetTimeout
AndSetinterval
Differences:
SetTimeout (function (){
/* Some long block of code ...*/
SetTimeout (arguments. callee, 10 );
}, 10 );
Setinterval (function (){
/* Some long block of code ...*/
}, 10 );
At first glance, there is no difference between the two sentences, but they are different. The interval between the execution of the setTimeout callback function and the last execution is at least 10 ms (more, but not less than 10 ms ), the callback function of setinterval will try to run every 10 ms, regardless of whether or not the last execution is complete.
Here we have learned a lot of knowledge, to sum up:
- The JavaScript engine is single-threaded and forces all asynchronous events to be queued for execution.
SetTimeout
AndSetinterval
There are fundamental differences in executing asynchronous code
- If a timer is blocked and cannot be executed immediately, it will be executed until the next possible execution time point (longer than the expected interval)
- If
Setinterval
The execution time of callback functions will be long enough (longer than the specified interval), and they will be executed continuously and there is no time interval between them.
These knowledge points are very important. Understanding how the JavaScript engine works, especially when a large number of asynchronous events (continuous) occur, can lay a solid foundation for building advanced applications.
The original English text is as follows:
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 );
-SimilarSetTimeout
But continually callthe 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 written ed: 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 digoal, like in the following:
Size: 500x375
Browsing: 613 times
Click Open new window to view the full graph "border =" 0 ">
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 distriis one dimends: 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 18 ms, the mouse click block for approxiely 11 ms, 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 10 msSetTimeout
And a 10 msSetinterval
. 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 wocould 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 sacriiced.
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 50 ms 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 between strate the differencesSetTimeout
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. NotablySetTimeout
Code will always have at least a 10 ms delay after the previous callback execution (it may end up being more, but never less) whereasSetinterval
Will attempt to execute a callback every 10 ms regardless of when the last callback was executed.
There's a lot that we 've ve learned here, let's recap:
- Javascript Engines only have a single thread, forcing asynchronous events to queue waiting for execution.
SetTimeout
AndSetinterval
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. 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.