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

May 16, 2016 pm 05:37 PM
setinterval settimeout

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.
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
What is the difference between settimeout and setinterval What is the difference between settimeout and setinterval Aug 15, 2023 pm 02:06 PM

The difference between settimeout and setInterval: 1. Trigger time, settimeout is one-time, it executes the function once after setting the delay time, while setinterval is repetitive, it will execute the function repeatedly at the set time interval; 2. Execution times, settimeout is only executed once, and setinterval will be executed repeatedly until canceled.

How to use setInterval function to execute code regularly? How to use setInterval function to execute code regularly? Nov 18, 2023 pm 05:00 PM

How to use setInterval function to execute code regularly? In JavaScript, the setInterval function is a very useful function, which can execute a piece of code regularly. Through the setInterval function, we can repeatedly execute specified code within a specific time interval. This article will introduce in detail how to use the setInterval function and provide specific code examples. 1. The basic syntax of the setInterval function is as follows: setInterv

How to use the Window.setInterval() method How to use the Window.setInterval() method Aug 31, 2023 am 09:33 AM

The basic syntax of the Window.setInterval() method is "window.setInterval(function, delay)", function is the function or code block to be executed repeatedly, and delay is the time interval between each execution, in milliseconds. This method is a method in JavaScript used to repeatedly execute a specified function or code at a scheduled time. Its use is very simple. You only need to pass in the function or code block to be executed and the time interval for repeated execution.

Detailed explanation of setinterval usage Detailed explanation of setinterval usage Sep 12, 2023 am 09:55 AM

The usage of setinterval is "setInterval(function, delay);", "function" is the function to be executed, which can be a function expression or function reference, and "delay" is the time interval between executing functions, in milliseconds. setInterval is a function in JavaScript that is used to execute code periodically. It accepts a function and a time interval as parameters, and will execute the function repeatedly according to the specified time interval.

Use the clearTimeout function in JavaScript to cancel the setTimeout timer Use the clearTimeout function in JavaScript to cancel the setTimeout timer Nov 18, 2023 am 08:05 AM

To use the clearTimeout function in JavaScript to cancel the setTimeout timer, you need specific code examples. In JavaScript, the setTimeout function is used to execute a specific code after a specified time delay. The setInterval function is used to repeatedly execute a specific code within a specified time interval. However, in some cases we may need to cancel the timer before it executes. In this case, you can use c

setInterval setInterval Aug 02, 2023 am 10:17 AM

The setInterval function is a timer function in JavaScript that allows you to set an interval and execute specified code after each interval. It is very useful when certain tasks need to be processed regularly or page elements are updated in real time. Pay attention to the following when using setInterval performance and reliability issues and optimize as needed.

How to stop setInterval How to stop setInterval Dec 11, 2023 am 11:39 AM

You can use the clearInterval function to stop a timer created by the setInterval function. The setInterval function returns a unique timer ID, which can be passed as a parameter to the clearInterval function to stop the execution of the timer.

What is the difference between setTimeout() and setInterval() in JavaScript? What is the difference between setTimeout() and setInterval() in JavaScript? Sep 01, 2023 pm 03:01 PM

setTimeout(function,duration) - This function calls the function after duration milliseconds. This works for one execution. Let's see an example - it waits for 2000 milliseconds and then runs the callback function alert('Hello') - setTimeout(function(){alert('Hello');},2000); setInterval(function,uration) - this function is The function is called after every duration milliseconds. This can be done an unlimited number of times. Let's see an example - it triggers an alarm every 2000 ms

See all articles