When SetTimeout () and setinterval () are called for execution (not multithreaded). Rp

Source: Internet
Author: User
Tags setinterval

Defined

SetTimeout () and setinterval () are often used to handle delays and timed tasks. SetTimeout The () method is used to call a function or evaluate an expression after a specified number of milliseconds, and setinterval() can loop through a function or expression every specified number of milliseconds until clearinterval clears it.

From the definition we can see that two functions are very similar, except that the former executes once, while the latter can be executed more than once, the parameters of two functions are the same, the first parameter is the code or handle to execute, the second is the number of milliseconds to delay.

Very simple definition, it is very simple to use, but sometimes our code is not according to our imagination precise time is called, it is confusing

Simple example

To see a simple example, a simple page after two seconds of loading, write down delayed alert!

SetTimeout (' document.write ("Delayed alert!"); ', 2000);

Looks reasonable, let's look at an example of a setinterval () method

var num = 0;        var i = setinterval (function() {            num++new Date (); document.write (date.getminutes () + ': ' + date . getseconds () + ': ' + date.getmilliseconds () + ' <br> 'if (num >) clearinterval (i);}, +); 

The page records the current time (minutes: seconds: milliseconds) Every 1 seconds, records 10 times and clears, no longer records. Consider that the execution time of the code may not be recorded, but the time interval should be the same, and look at the results

43:38:11643:39:13043:40:14443:41:15843:42:17243:43:18643:44:20043:45:21443:46:22843:47:24243:48:256

Why

The time interval is almost 1000 milliseconds, but imprecise, what is this for? The reason for this is that we have a misconception about JavaScript timers thatJavaScript is actually running in a single-threaded environment , which means that the timer is only going to be executed at some time in the future, and The timing of execution is not guaranteed because there may be other code in the control of the JavaScript process at different times in the life cycle of the page. After the page is downloaded, the code runs, the event handlers, the AJAX callback functions are all using the same thread, and the browser is actually responsible for sorting, assigning a program the priority to run at a certain point in time.

Let's zoom in and see, add a time-consuming task

functionTest () {for (var i = 0; I < 500000; i++) {var div = document.createelement (' div ' var num = 0; var i = setinterval (function  () {Num++var date = new date (); document.write (date.getminutes () + ': ' + date.getseconds () + ': ' + date.getmilliseconds () + ' <br> ' 

We added a timed mission to see the results.

47:9:22247:12:48247:16:847:19:14347:22:63147:25:88847:28:71247:32:38147:34:14647:35:56547:37:406

This effect is obvious, the gap is even more than 3 seconds, and the gap is very inconsistent.

We can think of JavaScript as running on the timeline. The first thing to do when the page is loaded is the method and variable declaration and data processing that will be used after the page life cycle, after which the JavaScript process waits for more code execution. When the process is idle, the next piece of code is triggered

In addition to the main JavaScript process, you need a code queue that executes the next time the process is idle. As the page life cycle progresses, the code is added to the queue in order of execution, for example, when the button is pressed, his event handlers are added to the queue and executed within the next possible time. When an AJAX response is received, the code for the callback function is added to the queue. no code in JavaScript is executed immediately, but once the process is idle it executes as soon as possible. the way a timer works on a queue is when the code is inserted after a certain time has passed, which does not mean that it executes immediately, only that it executes as quickly as possible.

Knowing this, we can understand that if you want precise time control, you can't rely on JavaScript's settimeout function.

Repetitive timers

The timer created with SetInterval () allows the code to be executed in a loop, and when the effect is specified, the interval can be cleared, as in the following example

var my_interval = setinterval (function () {            if (condition) {                //else { Clearinterval (My_interval); }}, (+);      

However, the problem with this approach is that the code of the timer may not be completed before the code is added to the queue again, resulting in inaccurate judgment conditions within the loop, multiple executions of the code, and no pauses between them. JavaScript has solved this problem, however, when using setinterval (), the timer code is inserted into the queue only if no other code instance of the timer is available. This ensures that the minimum time interval for the timer code to join the queue is the specified interval.

This rule brings two questions.

    1. 1. Some intervals are skipped
    2. 2. The interval between code execution for multiple timers may be smaller than expected

To avoid these two drawbacks, we can use settimeout () to implement a repeating timer

SetTimeout (function () {            //code            setTimeout (Arguments.callee, interval);        }, Interval)    

This creates a new timer every time the function executes, and the second settimeout () call uses Agrument.callee to get a reference to the currently executing function and to set up another new timer. This ensures that there will be no new timer insertions until the execution of the code is completed, and that the next timer code must be at least spaced for a specified period of time to avoid running continuously.

SetTimeout (function () {            var div = document.getElementById (' movediv ');            var left = parseint (div.style.left) + 5, Div.style.left = left + ' px 'if (left < +) {setTimeout (Argu Ments.callee, (); }}, ();        

Each time the timer code executes, move a div to the right 5px, and stop when the coordinates are greater than 200.

Text turn: http://www.cnblogs.com/dolphinX/archive/2013/04/05/2784933.html

When SetTimeout () and setinterval () are called for execution (not multithreaded). Rp

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.