The basics of when settimeout () and SetInterval () in JS are invoked for execution

Source: Internet
Author: User
Tags current time setinterval time interval

Defined
SetTimeout () and setinterval () are often used to handle delays and timed tasks. The settimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds, and setinterval () can loop through the function or expression at the specified number of milliseconds, until clearinterval clears it.
We can see from the definition that two functions are very similar, except that the former executes once, while the latter can execute multiple times, and the parameters of the two functions are the same, the first parameter is the code or handle to execute, and the second is the number of milliseconds to delay.
Simple definition, it's easy to use, but sometimes our code is not as accurate as we think it is called, it's confusing.


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

Copy Code code as follows:

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

Looks reasonable, let's look at an example of a setinterval () method
Copy Code code as follows:

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

The page records the current time (minutes: seconds: milliseconds) Every 1 seconds, and the records are cleared after 10 times, and are no longer recorded. Considering that the code execution time may not record execution time, but the time interval should be the same, look at the results
Copy Code code as follows:

: 38:116
: 39:130
: 40:144
: 41:158
: 42:172
: 43:186
: 44:200
: 45:214
: 46:228
: 47:242
: 48:256

why
The time interval is almost 1000 milliseconds, but not accurate, what is this? The reason is that we have a misunderstanding of the JavaScript timer, JavaScript is actually running in a single-threaded environment, which means that the timer is only planning to execute at some point in the future, and the specific execution time is not guaranteed, because the page life cycle, There may be other code at different times to control the JavaScript process. When the page is downloaded, the code runs, event handlers, Ajax callback functions use the same thread, and in fact the browser is responsible for sorting and assigning the priority of a program to run at a point in time.
Let's enlarge the effect to see if we add a time-consuming task
Copy Code code as follows:

function Test () {
for (var i = 0; i < 500000; i++) {
var div = document.createelement (' div ');
Div.setattribute (' id ', ' testdiv ');
Document.body.appendChild (DIV);
Document.body.removeChild (DIV);
}
}
SetInterval (test, 10);
var num = 0;
var i = setinterval (function () {
num++;
var date = new Date ();
document.write (date.getminutes () + ': ' + date.getseconds () + ': ' + date.getmilliseconds () + ' <br> ');
if (num > 10)
Clearinterval (i);
}, 1000);

We added a timed task to see the results.
Copy Code code as follows:

: 9:222
: 12:482
: 16:8
: 19:143
: 22:631
: 25:888
: 28:712
: 32:381
: 34:146
: 35:565
: 37:406

The 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. When the page is loaded, the first execution is the method and variable declarations and data processing to be followed by 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, code is added to the queue in the order in which it is executed, such as when the button is pressed, and his event handler is 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. There is no code in JavaScript that executes immediately, but executes as soon as the process is idle. The way a timer works on a queue is when the code is inserted after a certain time, which does not mean that it executes immediately, only that it executes as quickly as possible.
Knowing this, we can see that if you want accurate time control, you can't rely on JavaScript's settimeout function.

Repeat Timer
The timer created with SetInterval () allows the code to loop through, and when the effect is specified, the interval can be cleared, as in the following example
Copy Code code as follows:

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

But the problem with this approach is that the timer code may not have been completed before the code was added to the queue, resulting in inaccurate judgment in the loop, a few more executions, and no pauses. However, JavaScript has solved this problem, and when using setinterval (), the timer code is inserted into the queue only if there is no other code instance for the timer. This ensures that the minimum time interval for the timer code to join the queue is the specified interval.

Such a rule brings two questions

1.1. Some intervals will be 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 repetitive timer
Copy Code code as follows:

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 set up another new timer. This ensures that there will be no new timer inserts until the code is finished, and that the next timer code should be spaced at least a specified time before it is executed, to avoid running continuously.
Copy Code code as follows:

settimeout (function () {
var div = document.getElementById (' Movediv ');
var left = parseint (div.style.left) + 5;
Div.style.left = left + ' px ';
if (left < 200) {
SetTimeout (Arguments.callee, 50);
}
}, 50);

Each time the timer code executes, it moves a div to the right 5px, stopping when the coordinates are greater than 200.

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.