Home > Web Front-end > JS Tutorial > Usage of when setTimeout() and setInterval() are called and executed in JS_Basic knowledge

Usage of when setTimeout() and setInterval() are called and executed in JS_Basic knowledge

WBOY
Release: 2016-05-16 17:37:15
Original
1530 people have browsed it

Definition
setTimeout() and setInterval() are often used to handle delayed and scheduled tasks. The setTimeout() method is used to call a function or calculated expression after a specified number of milliseconds, while setInterval() can call a function or expression in a loop every specified number of milliseconds until clearInterval clears it.
From the definition, we can see that the two functions are very similar, except that the former is executed once, while the latter can be executed multiple times. The parameters of the two functions are also the same. The first parameter is the code or handle to be executed. The second parameter is the code or handle to be executed. Two are the number of milliseconds of delay.
Very simple definition and easy to use, but sometimes our code is not called at the exact time we imagined, which is very confusing


Simple example
Look at a simple example. After loading a simple page for two seconds, write Delayed alert!

Copy code The code is as follows:

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

It looks reasonable, let’s take a look Examples of setInterVal() method
Copy code The code is as follows:

var num = 0;
var i = setInterval(function() {
num ;
var date = new Date();
document.write(date.getMinutes() ':' date.getSeconds() ': ' date.getMilliseconds() '
');
                                                                                                                                                                           The current time (minutes: seconds: milliseconds) is recorded every 1 second. After recording ten times, it is cleared and no longer recorded. Considering that the code execution time may not record the 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 it is not precise. Why is this? The reason is that we have a misunderstanding about JavaScript timers. JavaScript actually runs in a single-threaded environment, which means that the timer only plans the code to be executed at a certain time in the future, and the specific execution time cannot be guaranteed. Because during the life cycle of the page, other code may be controlling the JavaScript process at different times. After the page is downloaded, the code running, event handler, and Ajax callback function all use the same thread. In fact, the browser is responsible for sorting and assigning the priority of a certain program to run at a certain point in time.
Let’s zoom in on the effect and add a time-consuming task


Copy the code
The code is 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 (); ':' date.getSeconds() ':' date.getMilliseconds() '
');
                                                                                         


We have added another scheduled task to see the results


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


The effect is obvious now, the gap is even smaller It's over 3 seconds, and the gap is very inconsistent.
We can think of JavaScript as running on a timeline. When the page loads, the first thing to be executed is the method and variable declaration and data processing to be used later in the page life cycle. After that, the JavaScript process will wait for more code to be executed. When the process is idle, the next piece of code will be triggered

In addition to the main JavaScript process, a queue of code is also needed to be executed the next time the process is idle. As the page life cycle goes by, code will be added to the queue in order of execution. For example, when a button is pressed, its event handler will be added to the queue and executed at the next possible time. When an Ajax response is received, the callback function code is added to the queue. No code in JavaScript is executed immediately, but as soon as the process is idle. The way a timer works on a queue is that code is inserted when a specific time has elapsed, this doesn't mean it will execute right away, it just means it will execute as soon as possible.
After knowing this, we can understand that if we want precise time control, we cannot rely on JavaScript's setTimeout function.


Repeating timer
The timer created using setInterval() can make the code execute in a loop. When the specified effect is achieved, just clear the interval, as in the following example


Copy code The code is as follows:var my_interval = setInterval(function () {
     if (condition ) {
                                                                                                                                                      🎜>

But the problem with this method is that the timer code may not be executed before the code is added to the queue again. As a result, the judgment conditions in the loop are inaccurate and the code is executed several times without pauses in between. However, JavaScript has solved this problem. When using setInterval(), the timer code is only inserted into the queue when there is no other code instance of the timer. This ensures that the minimum time interval for the timer code to be added to the queue is the specified interval.

Such a rule brings two problems

1.1. Some intervals will be skipped
2.2. The interval between code executions of multiple timers may be smaller than expected
In order to avoid these two shortcomings, we can use setTimeout() to implement repeated timers
Copy code The code is as follows ; In this way, a new timer will be created every time the function is executed. The second setTimeout() call uses agrument.callee to obtain a reference to the currently executing function and set another new timer. This ensures that no new timer will be inserted before the code execution is completed, and that there must be at least a specified time interval before the next timer code is executed to avoid continuous running.



Copy code

The code is 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); 5px, stop when the coordinate is greater than 200.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template