Delve into JavaScript timer _javascript tips

Source: Internet
Author: User
Tags setinterval time interval

JavaScript single Thread

A single thread of JavaScript, which is related to its purpose. As a browser scripting language, the main purpose of JavaScript is to interact with the user and manipulate the DOM. This determines that it can only be single-threaded, or it can create complex synchronization problems. For example, assuming that JavaScript has two threads at the same time, one thread adds content to one of the DOM nodes, and another thread deletes the node, which thread should the browser use? Therefore, in order to avoid complexity, from the birth, JavaScript is a single thread, which has become the core characteristics of the language, will not change in the future.

Queue tasks

A single thread means that all tasks need to be queued and the previous task is completed before the latter task is performed. If the previous task takes a long time, the latter task will have to wait all the time.


Asynchronous event-driven

Many of the actions in the browser are asynchronous (asynchronized), such as mouse click events, window Size drag events, timer triggering events, XMLHttpRequest completion callbacks, and so on. 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 handles events. For example, the browser is currently busy processing the OnClick event, when another event occurs (such as window OnSize), the asynchronous event is placed in the event queue for processing, and only the previous processing is complete and idle to execute the event.

Event Loop

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

Browsers will have at least some of the following processes

1. Browser GUI render Thread

2.JavaScript engine Thread

3. Browser Timer 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 into the queue and then run by the engine in a first-in, first-out manner. Event-handler functions, timer execution functions are also queued, and then an infinite loop is used to remove function execution from the team head, which is the event Loop.

summed up in one word, JS is single-threaded, but the browser is multi-threaded, encountered asynchronous things are the browser to the asynchronous callback into the event loop, JS thread is not busy, and then read the event loop

Timer principle

The use of Timers

settimeout (FN, delay)

SetInterval (FN, delay)

FN is either a function or a string, delay is the time of the delay, the unit is milliseconds

The following should be noted

1.fn can be a string, but it is not recommended to use this

2.fn inside the function if there is this, when executed this will point to the window above


If you understand the JS single thread and event loop, the principle of the timer is well understood

If the timer is set, when the delay time, the browser will delay the execution of events into the event loop, when the time is up, if the JS thread idle will be executed (so the accuracy of the timer is not allowed AH)


See an article Introduction said settimeout and SetInterval on the function has been polling the difference, the code is as follows

Copy Code code as follows:

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

The article probably means that settimeout is the callback function after the launch of the next timer, so there must be an interval of execution, and setinterval is always in the execution, if you hit the JS thread has been executing, may be in the event loop with multiple callbacks, When the JS thread is not busy, it will execute multiple

After the test found that no matter under Ie,ff,chrome,opera,safari, setinterval are at a certain interval

The test code is as follows

Copy Code code as follows:

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

for (Var i=0;i<6000000;i++) {
Xx.offsetwidth
}

settimeout (function () {
Debugger
},10)

The breakpoint was printed with only a 1

The precision problem of timer

Because of JS single thread reason, if encountered busy, the timer is definitely not allowed, and certainly is more and more long, this seems to have no solution ah, no solution AH

There is also a precision problem is the minimum interval settimeout (fun,0)

When the JS thread is not busy, it is not possible to execute immediately after 0 seconds, there is always a minimum interval, each browser is different, this did not do the test

I read an article that is the standard of the consortium, the minimum time to execute the timer is 4ms, can not find the source of research AH!!!

Some optimizations related to timers

You can still have some optimizations when you're doing the timer.

1. For example, if the binding window.onresize, in the browser zoom, the trigger is very frequent, so you can delay execution, when the next execution to clear out, reduce the frequent execution

Pseudo code is as follows

Copy Code code as follows:

var timer;
function R () {
Cleartimeout (timer);
Timer = settimeout (function () {
Do something
},150);
}

2. In the scroll down the time is also a bit, such as the picture of the lazyload, there should be a timer to avoid too much calculation

3. When there are multiple places to need the timer, you can combine into a timer, the time interval with the smallest one, and then need to execute the callback function to the array inside plug, when the time interval, traversal array execution can

A small demo

Copy Code code as follows:

<! DOCTYPE html>
<meta charset= "Utf-8"/>
<style>
wrap{width:80% margin:30px Auto; border:1px solid #ccc; padding:20px;
. c{border:1px solid #ccc; height:30px;margin-bottom:20px;}
</style>
<body>
<div id= "XX" ></div>
<div class= "Wrap" >
<div id= "A1" class= "C" >0</div>
<div id= "A2" class= "C" >0</div>
<div id= "A3" class= "C" >0</div>
<div id= "A4" class= "C" >0</div>
</div>
<script src= "Http://static.paipaiimg.com/paipai_h5/js/ttj/zepto.min.js "></script>
<script type= "Text/javascript" >
var runTime = {
Options: {
step:1000
},
Callbacks:[],
Addcallbacks: [],
Start:false,
Timer:null,
Extend:function () {
var target = Arguments[0] | | {}, I = 1, length = arguments.length, options;
if (typeof target!= "Object" && typeof target!= "function")
target = {};
for (; i < length; i++)
if (options = arguments[i])!= null)
for (var name in options) {
var copy = options[name];
if (target = = copy)
Continue
if (copy!== undefined)
target[name] = copy;
}
return target;
},
Init:function (options) {
$.extend (this,this.options,options| | {});
},
Add:function (fun,options) {
options = Options | | {};
This.addCallbacks.push ({
Fun:fun,
Starttime:new Date (). GetTime (),
Step:options.step | | This.step,
I:1
});
var self = this;
if (!this.start) {
This.callbacks = [fun];
This.start = true;
This.starttime = new Date (). GetTime ();
This.timer = setinterval (function () {
Self.done ();

},THIS.STEP);
}
},
Done:function () {
var callbacks = This.callbacks,
Self = this,
NEWARR = [];
$.each (Callbacks,function (i,obj) {
if (Obj.step = = Self.step) {
Obj.fun ();
}else{
if (obj.i = = Obj.step/self.step) {
if ((New Date (). GetTime ())-OBJ.STARTTIME&GT;OBJ.STEP*2/3) {
Obj.fun ();
}
OBJ.I = 1;
}else{
OBJ.I = obj.i + 1;
}
}
});
$.each (This.addcallbacks,function (i,obj) {
if (Obj.step = = Self.step) {
if ((New Date (). GetTime ())-OBJ.STARTTIME&GT;OBJ.STEP*2/3) {
Obj.fun ();
Callbacks.push (obj);
}else{
Newarr.push (obj);
}
}else{
OBJ.I = obj.i + 1;
Callbacks.push (obj);
}
});
This.addcallbacks = NEWARR;
},
Clear:function () {
Clearinterval (This.timer);
}
}
Runtime.init ();

Runtime.add (function () {
a1.innerhtml = ~~a1.innerhtml+1;
});

Runtime.add (function () {
a2.innerhtml = ~~a2.innerhtml+1;
},{step:2000});

Runtime.add (function () {
a3.innerhtml = ~~a3.innerhtml+1;
},{step:4000});
Runtime.add (function () {
a4.innerhtml = ~~a4.innerhtml+1;
},{step:8000});
</script>
</body>

Do you have any idea about the JavaScript timer, and if you have any questions, leave a message for me.

Related Article

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.