如何使用Node.js的计时器

716 阅读3分钟

Node.js定时器入门

简介

Node.js有几个实用程序,我们可以用来安排我们的代码的执行。与大多数Node.js模块不同,定时器模块没有被导入。这些方法可以全局访问,以提供与JavaScript浏览器API的一致性。

在本教程中,我们将研究Node.js的定时器模块,以及我们如何使用这个工具来控制代码的执行。

目录

  1. 安排定时器
  2. 取消定时器
  3. 摘要

前提条件

要继续学习本教程,读者应该具备以下条件。

  1. 在你的开发环境中安装了Node.js。在本教程中,我们使用v15.12。
  2. 具备基本的JavaScript知识。

目标

在本教程结束时,你应该能够控制一些代码块的执行。

使用setTimeout()方法调度定时器

如前所述,Node.js API提供了一些实用工具,使我们能够根据我们的要求在稍后的时间执行代码。

在本节中,我们将看看Node.js的setTimeout() 方法。这个方法是用来安排在给定的时间段后执行代码的,单位是毫秒

语法

let timeoutId = setTimeout(func[, delay, argument1, argument2, ...]);// syntax option 1
let timeoutId = setTimeout(func[, delay]); // option 2
let timeoutId = setTimeout(code[, delay]); // option 3

例子

function myTimerFunction(argument) 
{ 
    console.log(`argument was => ${argument}`);
} 

setTimeout(myTimerFunction('John Doe'), 5000);

在上面的例子中,我们已经定义了myTimerFunction() 方法。然后在一个setTimeout() 方法中调用这个方法,在5秒后执行。

输出


"argument was => John Doe"

注意:Node.js中的setTimeout() 与JavaScript API中的window.setTimeout() 略有不同,因为它不接受字符串。还需要注意的是,由于代码阻塞等其他因素的影响,setTimeout() 不能完全依赖。

使用setInterval()方法调度定时器

setTimeout() 不同,这个方法用于多次执行代码。例如,公司Section可能每周向其Edge as a Service客户发送新闻简报。这就是setInterval() 方法的一个例子。它是一个无限循环,只要不退出(或停止)就会执行。

它的语法如下。

let intervalId = setInterval(callbackFunction, [delay, argument1, argument2, ...]); //option 1
let intervalId = setInterval(callbackFunction[, delayDuration]); // option 2
let intervalId = setInterval(code, [delayDuration]); //option 3

我们来看看一个例子。

function intervalFunction() 
{ 
    console.log('This interval is printed after 2 seconds!');
} 

setInterval(intervalFunction, 2000);

20秒后输出。

This interval is printed after 2 seconds!
This interval is printed after 2 seconds!
This interval is printed after 2 seconds!
This interval is printed after 2 seconds!
This interval is printed after 2 seconds!
This interval is printed after 2 seconds!
This interval is printed after 2 seconds!
This interval is printed after 2 seconds!
This interval is printed after 2 seconds!
This interval is printed after 2 seconds! 

在上面的例子中,intervalFunction() ,每2秒执行一次,直到它被退出(停止)。

使用setImmediate()方法调度定时器

setImmediate() 方法是用来在循环周期的末端执行代码的。简单地说,这个方法打破了那些需要较长时间执行的任务,以运行由其他操作(如事件)发起的回调函数。

setImmediate() ,该函数的语法如下。

let immediateId = setImmediate(callbackFunction, [param1, param2, ...]);
let immediateId = setImmediate(callbackFunction);

我们来看看一个例子。

console.log('before set immediate function is called'); 

setImmediate((arg) => 
{ 
    console.log(`executing the immediate function: ${arg}`);
}); 

console.log('after immediate function has been executed');

输出

before a set immediate function is called
after the immediate function has been executed
executing the immediate function: undefined

在执行这个方法时,你很可能会遇到一个错误,如下图所示。如果你没有遇到这个错误,请跳过这一部分。

before a set immediate function is called
error: ReferenceError: setImmediate is not defined

setImmediate() 方法不被大多数浏览器所支持。因此,它抛出了一个ReferenceError: setImmediate is not defined

要解决这个问题,只需在脚本的顶部添加以下脚本。

window.setImmediate = window.setTimeout;

这一行允许我们将setTimeout() 赋给全局setImmediate() 方法。

需要注意的是,这种方法 (setImmediate()) 不太可能成为浏览器的标准。

有了关于setImmediate() 的基本知识,让我们来看看一个稍微高级的嵌套函数的例子。

timer.js 脚本文件中,添加以下内容。

setImmediate(function functionA() {
    setImmediate(function functionB() {
        console.log(10);

        setImmediate(function functionD() {
            console.log(20);
        });
    });
    setImmediate(function functionC()

        {
            console.log(30);

            setImmediate(function functionE() {
                console.log(40);
            });

        });
});

console.log('You have started set immediate:...');

输出

You have started set immediate:...
10
30
20
40

在上面的脚本中,我们调用了几个排队的方法,即functionA(),functionB,functionC,functionD, 和functionE

它们都是在事件循环完成后执行的。嵌套的回调不被执行 立即,直到下面的循环。

这就解释了为什么我们有无序的输出。

取消定时器

现在我们已经学会了如何安排任务,如果我们需要停止/取消时间表怎么办?我们讨论过的这3个方法,即setTimeout(),setImmediate(), 和setInterval() ,都返回定时器对象。

当这个定时器对象被传递给clear() 方法时,这些方法的执行就完全停止了。

例子


let timeoutObject 
    =  setTimeout(() => 
        { 
            console.log('Timeout');
        }, 3000);
    
let intervalTimerObject 
    = setInterval(() =>
        { 
            console.log('Interval')
        }, 5000);
        
let immediateTimerObject
    = setImmediate(() => 
        {
            console.log('Immediate');
        }); 

clearTimeout(timeoutObject);
clearInterval(intervalTimerObject);
clearImmediate(immediateTimerObject);

结语

在本教程中,我们已经看到了使用Node.js定时器模块调度任务的过程。我们看到了如何设置超时,为重复性任务设置间隔计时器,以及如何使用set immediate绕过长操作。我们还看到了我们如何使用clear() 方法来停止这些操作。