In-depth Exploration of javascript timer _ javascript skills

Source: Internet
Author: User
Tags time in milliseconds
This article mainly introduces the in-depth exploration of javascript timers, which is very detailed and comprehensive. For more information, see Javascript single thread

The single thread of JavaScript is related to its purpose. As a browser scripting language, JavaScript is mainly used to interact with users and operate DOM. This determines that it can only be a single thread, otherwise it will bring a very complicated synchronization problem. For example, if JavaScript has two threads at the same time, one thread adds content to a DOM node, and the other thread deletes the node, which thread should the browser take as the standard? Therefore, in order to avoid complexity, JavaScript is a single thread from its birth, which has become the core feature of the language and will not change in the future.

Queue task

A single thread means that all tasks need to be queued and the previous task ends before the latter task can be executed. If the previous task takes a long time, it will have to wait.


Asynchronous event-driven

Many browser behaviors are asynchronous (Asynchronized), such as mouse click events, window size drag events, timer trigger events, and XMLHttpRequest complete callback. When an asynchronous event occurs, it enters the event queue. The browser has an internal large Message Loop, Event Loop, which polls large Event queues and processes events. For example, the browser is currently busy processing the onclick event, and another event (such as window onSize) occurs. This asynchronous event is put into the event queue for processing, this event will be executed only when the previous processing is complete and idle.

Event Loop

JavaScript is single-threaded, but the browser is not single-threaded

The browser has at least the following processes:

1. browser GUI rendering thread

2. JavaScript engine thread

3. browser timing trigger thread

4. browser event trigger thread

5. browser http asynchronous request thread

Because the JavaScript engine is single-threaded, the code is first pressed to the queue, and then the engine runs in the first-in-first-out mode. The Event processing function and the timer execution function will also be arranged in this queue, and then use an infinite Loop to continuously retrieve the function execution from the queue header. this is the Event Loop.

To sum up, JavaScript is single-threaded, but the browser is multi-threaded. asynchronous callback is put into Event Loop by the browser when JavaScript threads are not busy, read Event Loop again

Timer principle

Timer usage

SetTimeout (fn, delay)

SetInterval (fn, delay)

Fn can be a function or a string, and delay is the delay time in milliseconds.

Note the following:

1. although fn can be a string, it is never recommended to use this function.

2. if the function in fn has this, this will point to the window during execution.


If you understand the js single line and Event loop, the timer principle is also well understood.

If a timer is set, when the delay time is reached, the browser will put the delayed execution Event into the Event loop. when the time is reached, if the js thread is idle, it will be executed (so the timer accuracy is inaccurate)


I have read an article about the difference between setTimeout and setInterval in function polling. the code is as follows:

The code is as follows:


SetTimeout (function (){
SetTimeout (arguments. callee, 100)
}, 100)
SetInterval (function () {}, 1000)

The article probably means that setTimeout starts the next timer only after the callback function is executed, so there must be an interval of execution, while setInterval is always being executed, if the js thread is always executed, multiple callbacks may be added in the Event loop. when the js thread is not busy, multiple callbacks will be executed at once.

After tests, it is found that, in ie, ff, chrome, Opera, and Safari, setInterval comes at a certain interval.

The test code is as follows:

The code is as follows:


SetInterval (function (){
Xx. innerHTML = xx. innerHTML + 1;
},100 );

For (var I = 0; I <6000000; I ++ ){
Xx. offsetWidth
}

SetTimeout (function (){
Debugger;
}, 10)

When the breakpoint is broken, only one 1 is printed.

Timer precision problems

If the js is single-threaded and busy, the timer is definitely not allowed, and it must be longer and longer. it seems like there is no solution, no solution.

Another accuracy problem is the minimum interval setTimeout (fun, 0)

When the js thread is not busy, it cannot be executed immediately after 0 seconds. there is always a minimum interval, and each browser is different. this is not tested.

I have read an article about w3c standards. the minimum Time for Timer execution is 4 ms. you cannot find the source !!!

Timer-Related Optimization

Some optimizations can be made during timer creation.

1. for example, if you bind window. onresize to the browser, this trigger is very frequent during browser scaling, so execution can be delayed. when the next execution arrives, clear the trigger to reduce frequent execution.

The pseudocode is as follows:

The code is as follows:


Var timer;
Function r (){
ClearTimeout (timer );
Timer = setTimeout (function (){
// Do something
},150 );
}

2. when the scroll bar is pulled down, there should also be a timer for lazyload to avoid excessive computation.

3. when a timer is needed in multiple places, it can be merged into a timer. the minimum time interval prevails, and the callback function to be executed is inserted into the array. when the time interval is reached, execute the traversal array.

A small demo

The code is as follows:











0


0


0


0



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.