


Usage of when setTimeout() and setInterval() are called and executed in JS_Basic knowledge
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!
setTimeout('document.write("Delayed alert!");', 2000);
It looks reasonable, let’s take a look Examples of setInterVal() method
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
: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.
Copy the code
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
: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
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

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.

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.

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

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.

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.

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
