node js 中的 settimeout
settimeout()
函数是一个异步函数,用于在指定时间后执行一段代码。
这是我们可以用来调度 node js api 提供的代码的几种方法之一。此方法在窗口对象和服务器端都可用。
但是,它在服务器端的实现与 window 对象中使用的不同。
在 nodejs 中使用 settimeout()
函数
settimeout()
函数在 timers 模块下提供。该模块提供了各种方法,我们可以使用这些方法来安排函数在指定时间后调用。
由于 timer 对象是一个全局对象,因此在使用 settimeout()
函数时,我们的代码中不需要 require()
任何内容。
settimeout()
函数接受几个参数,包括:
- 该功能将在设定的时间间隔过后执行。
- 计时器在执行指定函数之前将等待的时间(以毫秒为单位)。
- 额外的可选参数。
此函数返回一个正整数
值,用于标识由对该函数的调用创建的计时器,通常称为 timeoutid
。
这是 settimeout()
函数的语法。
settimeout(function[, delay, arg1, arg2, ...]);
settimeout()
函数的一个简单示例,用于在函数之间暂停执行一定的毫秒数。
const display = () => {
console.log("some code to be executed !");
}
//function may contain more parameters
settimeout(display, 4000)
输出:
some code to be executed !
settimeout()
的异步特性在执行多个相互等待的函数时显露出来。在下面的示例中,执行第一个函数之前的平均等待时间为 6 秒
。
现在同时执行第二个函数。但是,由于执行第二个函数的平均等待时间是 4 秒
,因此最后一个函数首先执行,然后是第二个函数,最后是第一个函数。
settimeout(() => {console.log("this is the first statement")}, 6000);
settimeout(() => {console.log("this is the second statement")}, 4000);
settimeout(() => {console.log("this is the final statement")}, 2000);
输出:
this is the final statement
this is the second statement
this is the first statement
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
node.js 中的 http 发送 post 请求
发布时间:2023/03/27 浏览次数:456 分类:node.js
-
在本文中,我们将学习如何使用 node.js 使用第三方包发出发送 post 请求。