Node.js 描述使用Timer的方法
在本文中,我们将探讨Node.js中的计时器以及如何在各种情况下使用它们。Node.js的计时器方法包含不同类型的函数,用于在特定时间段执行一段代码或函数。它是一个全局模块,不需要导入。
我们可以将计时器模块分为两种类型的函数:
- 调度计时器: 这种类型的计时器用于在指定的时间段之后调用函数。
- 取消计时器: 这种类型的计时器用于取消已调度的计时器。
setImmediate()方法: 这是一种调度计时器,它安排立即执行回调函数。这些回调函数按照预定的时间排队,然后执行。这个事件循环迭代根据整个回调队列进行处理。当从执行回调函数排队任何立即计时器时,计时器将不会被触发。这只会持续到下一个事件循环迭代。
// Initializing multiple setImmediate() timer
setImmediate(function A() {
setImmediate(function B() {
console.log(1);
setImmediate(function D() {
console.log(2);
});
});
// Initializing other setImmediate timers
setImmediate(function C() {
console.log(3);
setImmediate(function E() {
console.log(4);
});
});
});
console.log('Started Timer Execution');
输出:
Started...
1
3
2
4
setInterval()方法 : 此方法以每个t毫秒调用一次的方式重复执行回调函数。
// Method will be executed 1000ms after start
setInterval(function intervalTimer() {
return console.log('Hey Geek! Welcome to Tutorials Point')
}, 1000);
// Executed when the program starts
console.log('This is executed before intervalTimer() method.');
输出:
This is executed before intervalTimer() method.
Hey Geek! Welcome to Tutorials Point
Hey Geek! Welcome to Tutorials Point
Hey Geek! Welcome to Tutorials Point
...
setTimeout()方法 : 该方法用于在指定的毫秒时间之后调用回调函数。超时时间作为参数传递给该方法。
// Method will be executed 3 seconds
// after the program starts
setTimeout(function setTimeout() {
return console.log('Hello Geek! Welcome to GFG');
}, 3000);
// Statement will be printed as soon as
console.log('Executed before setTimeout...');
输出:
Executed before A...
Hello Geek! Welcome to GFG
clearImmediate() 方法: 此方法用于取消使用 setImmediate() 调度方法创建的定时器。
// This method will clear the setImmediate() timer
const timer = setImmediate(function A() {
console.log("Timer is set");
});
// clearing the timer
clearImmediate(timer);
console.log("Timer is cleared");
输出:
Timer is cleared
clearInterval() 方法: 该方法用于取消使用 setInterval() 方法调度的定时器方法。
// This method will clear the setInterval() timer
// Setting the Interval timer
const timer = setInterval(function A() {
return console.log("Hello Geek!");
}, 500);
// Clearing the interval timer
setTimeout(function () {
clearInterval(timer);
console.log("Interval Timer cleared")
}, 2000);
输出:
Hello Geek!
Hello Geek!
Hello Geek!
Interval Timer cleared
clearTimeout() 方法 : 此方法用于清除使用setTimeout()方法设置的定时器。
// This method will clear the setTimeout() timer
// Setting the Timeout timer
const si1 = setTimeout(function A() {
return console.log("Hello World!");
}, 3000);
// Only the below method is executed
const si2 = setTimeout(function B() {
return console.log("Hello Geeks!");
}, 3000);
// Clearing timer 1
clearTimeout(si1);
输出:
Hello Geeks!