JavaScript provides the timer function, which can delay or repeatedly execute functions or code segments.
Method |
Description |
##setTimeout() | Call a function or execute a piece of code after the specified number of milliseconds |
setInterval() | Call a function or execute a piece of code according to the specified period (in milliseconds) |
clearTimeout() | Cancel the timer set by the setTimeout() method |
clearInterval() | Cancel the timer set by setInterval() |
The two timers are explained separately below.
setTimeout()
Create a timer:
setTimeout(() => console.log("我在两秒后被输出!"), 2*1000); // 1000 = 1s
// 执行上述代码,两秒后会在控制台输出:我在两秒后被输出!
Copy after login
There are 4 parameters in setTimeout(). Only two parameters are used here. The first The first parameter is an arrow function, and the second parameter indicates how many seconds to execute the arrow function. This process is called a callback, and this arrow function is called a callback function.
Callback function:
Pass a function as a parameter into another function, and then execute the passed function after the execution of the other function is completed. In the above code, the arrow function is passed into setTimeout() as a parameter. setTimeout() completes execution after two seconds, and then the arrow function starts to be executed, so the results we see will be output after a delay of two seconds.
Arrow function:
The meaning of arrow function is the same as that of ordinary function, but the expression is different. Because arrow functions are very concise, they are often embedded in other functions. If you want to learn more about it, please refer to other materials and will not go into details here.
Cancel timer:
When creating this timer, the unique identifier of this timer task will be returned:
let t = setTimeout(() => console.log("我在两秒后被输出!"), 2*1000); // 1000 = 1s
// t 即是一个标识符,但它不是我们认为的那种标识符,你可以打印出来试试!
Copy after login
clearTimeout () is used to cancel a scheduled task, provided that the scheduled task has not been triggered yet:
clearTimeout(t); // 传入定时任务的标识符
console.log("任务取消,两秒后我不会有任何输出!")
Copy after login
setInterval()
Create timer:
The usage of parameters is consistent with setTimeout(). The difference is that this timer will continue to execute in a loop. Run the following code to see the effect:
let t = setInterval(() => console.log("每隔一秒我会被输出一次!"), 1000)
Copy after login
Cancel timer:
clearInterval() is used to cancel the cyclic scheduled task, run the following code to see the effect:
let t = setInterval(() => console.log("每隔一秒我会被输出一次!"), 1000);
// 用上面学到的 setTimeout() 来取消循环定时任务
setTimeout(() => {
clearInterval(t);
console.log("我在五秒时被取消!");
;}, 5*1000);
Copy after login
Understanding the timer in depth
Before understanding the timer in depth, we need to understand the single thread of JavaScript . Because JavaScript is single-threaded, only one piece of code can be executed at a time. Task execution in JavaScript has the concept of a queue, that is, tasks will be queued and executed in the order of first in, first out.
setTimeout() timer demonstration:
let i = 0;
console.log(i);
setTimeout(() => console.log("我在两秒后被输出!"), 2*1000);
console.log("Hello world!");
Copy after login
Use animation to demonstrate the execution process of the following code:
The code in the program will be added to the queue one by one. When setTimeout() is executed, will not be added to the queue immediately , and the timer will be delayed by two seconds. During the timer delay, the program will not wait, but will directly execute the next piece of code, so "Hello world!" will be output in advance. After two seconds, the timer task will be added to the queue and the sentence "I will be output in two seconds!" is output.
I hope the animation can help everyone understand! The animation of the queue here is essentially not like this. The queue enters and exits. The timer task is added to the queue after two seconds. Since the program execution speed is very fast, the code in the queue has theoretically been executed. The queue at this time should is empty. Animation production is troublesome, so I did not delete the code in the queue. You can think of the code in the queue as code that has been executed.
setInterval() timer demonstration:
The theory is the same as setTimeout(), the difference is that setInterval() will add a scheduled task to the queue every once in a while.
There are some issues that need to be paid attention to when using setInterval(). For example, when the code encounters blocking, cyclically scheduled tasks will be accumulated. When the blocking ends, these accumulated tasks will be executed continuously regardless of the interval because they have been Add to queue. Look at the following demonstration:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>演示</title>
</head>
<body>
<script>
let t = setInterval(() => alert("我会阻塞程序!如果你不及时点确认的话。"), 2*1000);
</script>
</body>
</html>
Copy after login
Look at the execution results:
When the warning box pops up, click to confirm in time without causing obstruction. Therefore, the warning box It will pop up every second. Failure to click confirmation in time causes tasks to pile up and will be displayed continuously after the blocking is over.
setTimeout() implements loop timing:
let i = 0;
function timer() {
i++;
console.log(i);
// 函数内定时器的回调函数会继续调用 timer()
// 每秒自调用一次,因此实现类似死循环的效果
setTimeout( () => {
timer();
}, 1000);
}
// 启动函数
timer()
Copy after login
The program will output a value every second.
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of An in-depth analysis of timers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!