Front-end development: SetTimeout and SetInterval Timers and asynchronous loop arrays

Source: Internet
Author: User

            Front-end development: SetTimeout and SetInterval Timers and asynchronous loop arrays

 Objective:

three months since the opening of the blog park,   Essays Record the work encountered in the large and small problems, but also seen countless articles inspired by the article, I think this environment is excellent, in the sharing with Bo friends can learn new knowledge, get the pioneers to correct, solve the problem encountered in the work. Nearly one months of busy work, new articles have been slow to write, today, come here to learn more about JavaScript timer knowledge;

Brief introduction of SetTimeout and SetInterval

  

SetTimeout and SetInterval Use the same method, they accept two parameters, the first parameter is the function to execute, the second parameter is the execution of the delay time, see chestnuts:

SetTimeout (function() {    alert ("Hello");  The first parameter is a function, you can pass in the function name or an anonymous function},(); The second parameter is the delay time that  identifies the number of milliseconds after the execution of the previous function setinterval (function() {    alert ("Hello");} ,3000);

The only difference between settimeout and setinterval is that settimeout adds a task to the UI queue after the specified delay time arrives, the function executes immediately, and SetInterval adds the execution task to the UI queue at the specified delay time. If you do not clear it manually then the setinterval will continue until the page is closed, and if a task created by the same setinterval exists in the UI queue, then the successor task will not be added to the UI queue.

In layman's words, a function is executed after a specified time, and a function is executed at a specified time;

But what does it do in actual projects, we can use setinterval to make timed slides, real-time data updates, News list scrolling, The. Animate () method of jquery is to rely on the timer to simulate the animation effect; This blog implementation of this code, posted below with everyone to discuss: http://www.cnblogs.com/slowsoul/archive/2013/02/ 21/2921354.html javascript--Creating a motion frame

when it comes to timers, you have to first introduce a JavaScript runtime mechanism-- browser UI thread

Processes for executing JavaScript and updating the user interface are often referred to as "Browser UI Threads"

 In the browser, JavaScript execution and UI updates occur in the same process (browser UI thread). The work of the UI thread is based on a simple queue system, and the task is saved in the queue until the process is idle and executed. So JavaScript execution blocks UI updates, whereas UI updates block JavaScript execution. To the user's performance is the browser at work for a short or long time loss of response, the user's operation can not be timely response. The blocking of the UI thread is often due to the fact that we are going to do a lengthy script operation in the code that exceeds the browser limit, causing the browser to lose its response and freeze the user interface. Portal: JavaScript UI threading and performance optimizations

Using timers can asynchronously handle tasks that require a lot of computation, and it can avoid conflicts between UI updates and JavaScript execution in a timely manner

For example, in some extreme circumstances:

 for (var i=0;i<5000;i++) {    + = "Hello" +i;}

This code to the body insert string has been running 5,000 times, in Google browser This code will be executed about 3 seconds and this time the page is always blank and not operational, this is a very common performance problem, when dealing with a large number of operations, we can use deferred execution to separate the code into several sections to run, Can effectively improve the speed of code execution, and because it is asynchronous in the execution of the gap, the UI will start the update, so does not cause the page blank, user experience improved;

SetTimeout (function() {    for (var i=0;i<2500;i++) {        + = " Hello "+i;    }
Segmented processing 5,000 times into two segments setTimeout (function() { for(var i=0;i <2500;i++) { + = "Hello" +i; } },+);},100);

If you request a super-long news list to the server, because the volume of data is large and the single cycle parsing data lasts too long, you can use the timer decomposition task to process the data asynchronously

In general, we handle data like this:

for (Var i=0,len=msg.length;i<len;i++) {process (Msg[i])       }

Generally we use a for or while loop to parse the data, so the problem is that we have no way to control the page until the execution is complete, the larger the data the more obvious

Using Timer decomposition tasks

There are two prerequisites for using a timer decomposition task

1. Data processing does not need to be in a specific order

2. Whether synchronization must be processed, if it must be synchronized, then the timer does not apply;

The core theory is that the processing function of the current item is executed every time interval (usually 30 milliseconds, depending on the situation);

The code after encapsulation:

Volist:function(name,id,callback,time) {//settimeout Asynchronous Loop name is the array object ID that needs to be looped to the parse function to be executed time sets the duration of each run        if(time==undefined) {time=30;}; varFattr = Name.concat ();//cloning an arraySetTimeout (function(){            if(fattr.length>0) {ID (fattr.shift ()); //perform functions that run on each of the array itemssetTimeout (arguments.callee,time); }Else{callback ();//execution End callback function}},time);//Asynchronous Call time default}

There is another way to use the function in the array, the asynchronous loop call, the number of tasks to be executed into different sub-tasks, the phased execution of each:

functionfun1 () {alert (1)}functionfun2 () {alert (2)}functionFun3 () {alert (3)}
varFarr =[FUN1,FUN2,FUN3]; Store a task in an array settimeout (function(){ if(farr.length>0){ varFunc=farr.shift ();//removedFunc ();//Execute functionSetTimeout (arguments.callee,300); }Else{alert ("Execution Complete") }
},300);//300 sec Execution once

performance issues with timers

It is important to note that when there are multiple timers in a page, they perform too many tasks, often leading to unpredictable problems, and the solution is to avoid creating multiple timers, creating a separate timer, and allowing it to perform different tasks separately. In addition, each call to SetInterval () should be cleared before the previously useless setinterval, or to prevent duplication of the specified setinterval

var Timer // Clear First clearinterval (timer); // Call again  Timer = setinterval (function() {    ...},5000);

Summary

Reasonable use of timers can undoubtedly increase the overall performance of the page, in the processing of tasks that do not require synchronization, do not need sequential execution, you may consider using settimeout instead of the For loop asynchronous processing task;

---------------------------------------time never stopped its footsteps, how can you stop---------------------------------------

My number: QQ:

Welcome all kinds of technical discussion, if you have to build station needs, welcome to contact;

(reproduced please specify the source)

Front-end development: SetTimeout and SetInterval Timers and asynchronous loop arrays

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.