setTimeout(callback, delay[, ...args])


安排在 delay 毫秒之后执行一次性的 callback

callback 可能不会精确地在 delay 毫秒后被调用 。 Node.js 不保证回调被触发的确切时间,也不保证它们的顺序。 回调会在尽可能接近指定的时间被调用。

delay 大于 2147483647 或小于 1 时,则 delay 将会被设置为 1。 非整数的 delay 会被截断为整数。

如果 callback 不是函数,则抛出 TypeError

此方法有一个定制的用于 promise 的变体,使用 util.promisify() 创建:

const util = require('util');
const setTimeoutPromise = util.promisify(setTimeout);

setTimeoutPromise(40, 'foobar').then((value) => {
  // value === 'foobar' (传值是可选的)
  // 这会在大约 40 毫秒后执行。
});
  • callback <Function> The function to call when the timer elapses.
  • delay <number> The number of milliseconds to wait before calling the callback.
  • ...args <any> Optional arguments to pass when the callback is called.
  • Returns: <Timeout> for use with clearTimeout()

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using util.promisify():

const util = require('util');
const setTimeoutPromise = util.promisify(setTimeout);

setTimeoutPromise(40, 'foobar').then((value) => {
  // value === 'foobar' (passing values is optional)
  // This is executed after about 40 milliseconds.
});