Because in my daily work, some functions need to use timers, but timers are not as we see on the edge of the table, so THIS weekend I read books and looked up information, in-depth study of JavaScript timers, so no more nonsense, let’s enter the main topic today.

JavaScript is known to be single-threaded, so both timer and user actions need to be queued up in a thread queue.

A timer in the execution of thread queue analysis

I’m going to write a test code just to get a better understanding of it, just to make it a little bit more intuitive

 1 Copy the code

The above test code is divided into three parts:

1. Factorial calculation

2.setTimeout

3.setInterval

The general perception is that the factorial calculation will be performed first, and then setTimeout will be run after 10ms, and setInterval will be triggered every 10ms. On the face of it, that’s not necessarily the case.

Below I post the results of the code run to analyze one by one

As you can see from the results, the factorial function takes 15ms to run (multiple page refreshes may vary, so we’ll assume the factorial function takes 15ms).

At the beginning, a setTimeout timer with 10ms delay and a setInterval timer with 10ms interval will be started. Since the factorial function of the first stage takes 15ms, both the first two timers will expire at 10ms. Due to the single thread of JavaScript, These two timers need to enter the thread queue and wait until the first segment of the factorial function runs.

So you can see that setTimeout doesn’t start executing until 15ms, so that’s what I’m talking about. Even if you specify a timer, it doesn’t necessarily determine when the function will be executed. According to the printed result, it takes 5ms to complete setTimeout, so setInterval will be executed at 20ms.

What I’m talking about here is the time at which the three segments of the function start executing in the thread queue, not the time at which the function ends.

The difference between setTimeout and setInterval

Let’s go straight to the code for comparison

1     setTimeout(function cb(){
2         console.log("setTimeout");
3         setTimeout(cb,10);
4     },10);
5     setInterval(function(){
6         console.log("setInterval");
7     },10);Copy the code

The above code looks like it has the same function, but there is a difference between the two. In setTimeout, the callback function can be executed again after 10ms, while setInterval will execute the contents of the function every 10ms. Regardless of whether the last one was finished or not. That’s the difference between the two.

3. Reliability of timer delay time

After seeing the results posted in the first part, careful people may find that the timer delay I printed has a deviation of 1-2ms, which is the reliability of the delay time I want to see below

Without further ado, go directly to the test code (for the purpose of testing the effect, I will take an extreme point here and set the delay time to 1ms, so that the data results will be more obvious).

1 var time1 = new Date().getTime(); 2 setInterval(function(){ 3 var time2 = new Date().getTime(); 4 console.log("setInterval execution difference time: "+(time2-time1)); 5}, 1);Copy the code

In general, the result should be 1, 2, 3, 4, 5, 6, 8, 9…

But the actual results are as follows:

It can be seen that the average delay time is about 5ms. I tested it with Chrome browser. It is said that the average delay time varies with different systems and browsers.

Therefore, the timer delay time should not be set too small, because it may not be too small to achieve the effect you want (not excluding some really can control in 1ms or so awesome browser), and according to the device hardware or browser may delay time will have a small amount of error

Four, the small use of timer

Some would argue that timers can be useful, such as delaying device width by a few seconds when the screen is flipped.

What I want to talk about is not that but a way to use timers to improve performance.

First, let’s simulate a scenario where JS creates 100,000 DOM nodes on the fly, in which case the browser takes a lot of time to execute and blocks the execution of other code. It would be much better if we used a timer to break up the 100,000 DOM into multiple parts.

Five, reasonable management of timer

After a timer is known to all, with the need to clear, if not clear at the same time run multiple timers on one page, will loss performance page views make up a sense of caton, especially application of timer in animation, imagine, if make a animation effects with many of the timer, and multiple timer running at the same time, There is a chance that an animation that was supposed to be executed later will be executed ahead of time, which we don’t want to see.

So we have to do a reasonable management of timer according to the situation, or take animation as an example,

1. Animation must execute only one timer at a time;

2. You can flexibly control the start and close of the timer.

On the Internet can find the management of the timer example code, we can refer to:

1 var timers = { 2 timerID : 0, 3 timers : [], 4 add : function (fn) { 5 this.timers.push(fn); 6 }, 7 start : function (){ 8 if(this.timerID) return; 9 (function runNext(){ 10 if(timers.timers.length>0){ 11 for(var i=0; iCopy the code

View Code

In fact, the core of management is the two I mentioned above.

conclusion

1. If the timer cannot be executed immediately, the timer will queue up in the thread queue, waiting for the next executable point in time, so the timer may be longer than the set time, but not less than the set time;

2. SetTimeout and setInterval are quite different in the definition of being triggered;

3. Do not set the delay time of the timer to too small.

4. The use of timer can decompose a large number of operations of the code

5. Properly manage timers on the page

I wish you all a happy Qingming holiday! (That's just one more weekend than usual.)

Thank you for watching, any analysis of the wrong place welcome to point out the criticism, if you like this article, please click on the lower right corner of the recommendation oh ~

posted on
The 2016-04-02 now
Can only frostReading (
.Comment ()
The editor
collection