📜  Node.js 定时器模块

📅  最后修改于: 2022-05-13 01:56:53.893000             🧑  作者: Mango

Node.js 定时器模块

Node.js 中的Timers模块包含各种函数,这些函数允许我们在一段时间后执行一段代码或一个函数。 Timers 模块是全局的,我们不需要使用 require() 来导入它。

定时器模块具有以下功能:

  1. 调度定时器:用于在设定的时间段后调用函数。
    • 设置立即()
    • 设置间隔()
    • 设置超时()
  2. 取消定时器:用于取消预定的定时器。
    • 清除立即()
    • 清除间隔()
    • 清除超时()

1. setImmediate() 方法:它安排在 I/O 事件回调之后“立即”执行回调。在以下示例中,调用了多个 setImmediate 函数。每当我们这样做时,这些回调函数都会按照它们创建的顺序排队等待执行。每次事件循环迭代后都会处理整个回调队列。如果即时计时器从正在执行的回调中排队,则在下一次事件循环迭代之前不会触发该计时器。

setImmediate(function A() {
    setImmediate(function B() {
      console.log(1);
      setImmediate(function D() { 
        console.log(2);
      });
    });
  
    setImmediate(function C() {
      console.log(3);
      setImmediate(function E() { 
        console.log(4);
      });
    });
});
  
console.log('Started...');

输出:

Started...
1
3
2
4

在上面的例子中,在事件循环的第一次迭代中,函数A 被触发。然后在第二次迭代中触发函数B,并在第三次迭代中触发 C。同样,函数 D 和 E 分别在第四次和第五次迭代时触发。

2. setInterval() 方法:它在作为参数传递的每 t 时间(以毫秒为单位)后重复执行回调。

// Executed after every 1000 milliseconds
// from the start of the program
setInterval(function A() {
    return console.log('Hello World!');
}, 1000);
  
// Executed right away
console.log('Executed before A...');

输出:

Executed before A...
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
...

3. setTimeout() 方法:它以毫秒为单位安排回调的执行时间,作为参数传递。

// Executed after 3000 milliseconds 
// from the start of the program
setTimeout(function A() {
    return console.log('Hello World!');
}, 3000);
  
// executed right away
console.log('Executed before A...');

输出:

Executed before A...
Hello World!

4. clearImmediate() 方法:用于简单地取消setImmediate() 方法创建的Immediate 对象。

var si = setImmediate(function A() {
    console.log(1);
});
  
// clears setInterval si
clearImmediate(si);
  
console.log(2);

输出:

2

5. clearInterval() 方法:用于取消setInterval() 方法创建的Immediate 对象。

var si = setInterval(function A() {
    return console.log("Hello World!");
}, 500);
  
setTimeout(function() {
    clearInterval(si);
}, 2000);

clearInterval() 在 500 毫秒后清除 setInterval 'si',然后函数A 被执行四次。

输出:

Hello World!
Hello World!
Hello World!
Hello World!

6. clearTimeout() 方法:用于取消setTimeout() 方法创建的Immediate 对象。

// si1 is cleared by clearTimeout()
var si1 = setTimeout(function A() {
    return console.log("Hello World!");
}, 3000);
  
// only si2 is executed
var si2 = setTimeout(function B() {
    return console.log("Hello Geeks!");
}, 3000);
  
clearTimeout(si1);

只有 setInterval 'si2' 被执行,因为 'si1' 被 clearTimeout() 方法清除。
输出:

Hello Geeks!