0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-29 15:06:33 +01:00
nodejs/doc/api/timers.md

349 lines
11 KiB
Markdown
Raw Normal View History

2012-02-27 20:09:34 +01:00
# Timers
2010-10-28 14:18:16 +02:00
<!--introduced_in=v0.10.0-->
> Stability: 2 - Stable
The `timer` module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
globals, there is no need to call `require('timers')` to use the API.
2012-02-27 20:09:34 +01:00
The timer functions within Node.js implement a similar API as the timers API
provided by Web Browsers but use a different internal implementation that is
built around the Node.js [Event Loop][].
2010-10-28 14:18:16 +02:00
## Class: `Immediate`
2010-10-28 14:18:16 +02:00
This object is created internally and is returned from [`setImmediate()`][]. It
can be passed to [`clearImmediate()`][] in order to cancel the scheduled
actions.
By default, when an immediate is scheduled, the Node.js event loop will continue
running as long as the immediate is active. The `Immediate` object returned by
[`setImmediate()`][] exports both `immediate.ref()` and `immediate.unref()`
functions that can be used to control this default behavior.
### `immediate.hasRef()`
<!-- YAML
2018-10-23, Version 11.0.0 (Current) Notable changes: * Build * FreeBSD 10 is no longer supported.[#22617](https://github.com/nodejs/node/pull/22617) * `child_process` * The default value of the `windowsHide` option has been changed to `true`. [#21316](https://github.com/nodejs/node/pull/21316) * `console` * `console.countReset()` will emit a warning if the timer being reset does not exist. [#21649](https://github.com/nodejs/node/pull/21649) * `console.time()` will no longer reset a timer if it already exists. [#20442](https://github.com/nodejs/node/pull/20442) * Dependencies * V8 has been updated to 7.0. [#22754](https://github.com/nodejs/node/pull/22754) * `fs` * The `fs.read()` method now requires a callback. [#22146](https://github.com/nodejs/node/pull/22146) * The previously deprecated `fs.SyncWriteStream` utility has been removed.[#20735](https://github.com/nodejs/node/pull/20735) * `http` * The `http`, `https`, and `tls` modules now use the WHATWG URL parser by default. [#20270](https://github.com/nodejs/node/pull/20270) * General * Use of `process.binding()` has been deprecated. Userland code using `process.binding()` should re-evaluate that use and begin migrating. If there are no supported API alternatives, please open an issue in the Node.js GitHub repository so that a suitable alternative may be discussed. * An experimental implementation of `queueMicrotask()` has been added. [#22951](https://github.com/nodejs/node/pull/22951) * Internal * Windows performance-counter support has been removed. [#22485](https://github.com/nodejs/node/pull/22485) * The `--expose-http2` command-line option has been removed. [#20887](https://github.com/nodejs/node/pull/20887) * Timers * Interval timers will be rescheduled even if previous interval threw an error. [#20002](https://github.com/nodejs/node/pull/20002) * `util` * The WHATWG `TextEncoder` and `TextDecoder` are now globals. [#22281](https://github.com/nodejs/node/pull/22281) * `util.inspect()` output size is limited to 128 MB by default. [#22756](https://github.com/nodejs/node/pull/22756) * A runtime warning will be emitted when `NODE_DEBUG` is set for either `http` or `http2`. [#21914](https://github.com/nodejs/node/pull/21914)
2018-10-03 01:01:19 +02:00
added: v11.0.0
-->
* Returns: {boolean}
If true, the `Immediate` object will keep the Node.js event loop active.
### `immediate.ref()`
<!-- YAML
added: v9.7.0
-->
* Returns: {Immediate} a reference to `immediate`
When called, requests that the Node.js event loop *not* exit so long as the
`Immediate` is active. Calling `immediate.ref()` multiple times will have no
effect.
By default, all `Immediate` objects are "ref'ed", making it normally unnecessary
to call `immediate.ref()` unless `immediate.unref()` had been called previously.
### `immediate.unref()`
<!-- YAML
added: v9.7.0
-->
* Returns: {Immediate} a reference to `immediate`
When called, the active `Immediate` object will not require the Node.js event
loop to remain active. If there is no other activity keeping the event loop
running, the process may exit before the `Immediate` object's callback is
invoked. Calling `immediate.unref()` multiple times will have no effect.
## Class: `Timeout`
This object is created internally and is returned from [`setTimeout()`][] and
[`setInterval()`][]. It can be passed to either [`clearTimeout()`][] or
[`clearInterval()`][] in order to cancel the scheduled actions.
2010-10-28 14:18:16 +02:00
By default, when a timer is scheduled using either [`setTimeout()`][] or
[`setInterval()`][], the Node.js event loop will continue running as long as the
timer is active. Each of the `Timeout` objects returned by these functions
export both `timeout.ref()` and `timeout.unref()` functions that can be used to
control this default behavior.
2010-10-28 14:18:16 +02:00
### `timeout.hasRef()`
<!-- YAML
2018-10-23, Version 11.0.0 (Current) Notable changes: * Build * FreeBSD 10 is no longer supported.[#22617](https://github.com/nodejs/node/pull/22617) * `child_process` * The default value of the `windowsHide` option has been changed to `true`. [#21316](https://github.com/nodejs/node/pull/21316) * `console` * `console.countReset()` will emit a warning if the timer being reset does not exist. [#21649](https://github.com/nodejs/node/pull/21649) * `console.time()` will no longer reset a timer if it already exists. [#20442](https://github.com/nodejs/node/pull/20442) * Dependencies * V8 has been updated to 7.0. [#22754](https://github.com/nodejs/node/pull/22754) * `fs` * The `fs.read()` method now requires a callback. [#22146](https://github.com/nodejs/node/pull/22146) * The previously deprecated `fs.SyncWriteStream` utility has been removed.[#20735](https://github.com/nodejs/node/pull/20735) * `http` * The `http`, `https`, and `tls` modules now use the WHATWG URL parser by default. [#20270](https://github.com/nodejs/node/pull/20270) * General * Use of `process.binding()` has been deprecated. Userland code using `process.binding()` should re-evaluate that use and begin migrating. If there are no supported API alternatives, please open an issue in the Node.js GitHub repository so that a suitable alternative may be discussed. * An experimental implementation of `queueMicrotask()` has been added. [#22951](https://github.com/nodejs/node/pull/22951) * Internal * Windows performance-counter support has been removed. [#22485](https://github.com/nodejs/node/pull/22485) * The `--expose-http2` command-line option has been removed. [#20887](https://github.com/nodejs/node/pull/20887) * Timers * Interval timers will be rescheduled even if previous interval threw an error. [#20002](https://github.com/nodejs/node/pull/20002) * `util` * The WHATWG `TextEncoder` and `TextDecoder` are now globals. [#22281](https://github.com/nodejs/node/pull/22281) * `util.inspect()` output size is limited to 128 MB by default. [#22756](https://github.com/nodejs/node/pull/22756) * A runtime warning will be emitted when `NODE_DEBUG` is set for either `http` or `http2`. [#21914](https://github.com/nodejs/node/pull/21914)
2018-10-03 01:01:19 +02:00
added: v11.0.0
-->
* Returns: {boolean}
If true, the `Timeout` object will keep the Node.js event loop active.
### `timeout.ref()`
<!-- YAML
added: v0.9.1
-->
* Returns: {Timeout} a reference to `timeout`
When called, requests that the Node.js event loop *not* exit so long as the
`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect.
By default, all `Timeout` objects are "ref'ed", making it normally unnecessary
to call `timeout.ref()` unless `timeout.unref()` had been called previously.
### `timeout.refresh()`
<!-- YAML
2018-05-23, Version 10.2.0 (Current) * addons: - Fixed a memory leak for users of `AsyncResource` and N-API. (Michael Dawson) https://github.com/nodejs/node/pull/20668 * assert: - The `error` parameter of `assert.throws()` can be an object containing regular expressions now. (Ruben Bridgewater) https://github.com/nodejs/node/pull/20485 * crypto: - The `authTagLength` option has been made more flexible (Tobias Nießen) https://github.com/nodejs/node/pull/20235) https://github.com/nodejs/node/pull/20039 * esm: - Builtin modules (e.g. `fs`) now provide named exports in ES6 modules. (Gus Caplan) https://github.com/nodejs/node/pull/20403 * http: - Handling of `close` and `aborted` events has been made more consistent. (Robert Nagy) https://github.com/nodejs/node/pull/20075 https://github.com/nodejs/node/pull/20611 * module: - add --preserve-symlinks-main (David Goldstein) https://github.com/nodejs/node/pull/19911 * timers: - `timeout.refresh()` has been added to the public API. (Jeremiah Senkpiel) https://github.com/nodejs/node/pull/20298 * Embedder support: - Functions for creating V8 `Isolate` and `Context` objects with Node.js-specific behaviour have been added to the API. (Allen Yonghuang Wang) https://github.com/nodejs/node/pull/20639 - Node.js `Environment`s clean up resources before exiting now. (Anna Henningsen) https://github.com/nodejs/node/pull/19377 - Support for multi-threaded embedding has been improved. (Anna Henningsen) https://github.com/nodejs/node/pull/20542 https://github.com/nodejs/node/pull/20539 https://github.com/nodejs/node/pull/20541 PR-URL: https://github.com/nodejs/node/pull/20724
2018-05-14 20:01:36 +02:00
added: v10.2.0
-->
* Returns: {Timeout} a reference to `timeout`
Sets the timer's start time to the current time, and reschedules the timer to
call its callback at the previously specified duration adjusted to the current
time. This is useful for refreshing a timer without allocating a new
JavaScript object.
Using this on a timer that has already called its callback will reactivate the
timer.
### `timeout.unref()`
<!-- YAML
added: v0.9.1
-->
* Returns: {Timeout} a reference to `timeout`
When called, the active `Timeout` object will not require the Node.js event loop
to remain active. If there is no other activity keeping the event loop running,
the process may exit before the `Timeout` object's callback is invoked. Calling
`timeout.unref()` multiple times will have no effect.
Calling `timeout.unref()` creates an internal timer that will wake the Node.js
event loop. Creating too many of these can adversely impact performance
of the Node.js application.
## Scheduling timers
A timer in Node.js is an internal construct that calls a given function after
a certain period of time. When a timer's function is called varies depending on
which method was used to create the timer and what other work the Node.js
event loop is doing.
### `setImmediate(callback[, ...args])`
<!-- YAML
added: v0.9.1
-->
* `callback` {Function} The function to call at the end of this turn of
the Node.js [Event Loop][]
* `...args` {any} Optional arguments to pass when the `callback` is called.
* Returns: {Immediate} for use with [`clearImmediate()`][]
Schedules the "immediate" execution of the `callback` after I/O events'
callbacks.
When multiple calls to `setImmediate()` are made, the `callback` functions are
queued for execution in the order in which they are created. The entire callback
queue is processed every event loop iteration. If an immediate timer is queued
from inside an executing callback, that timer will not be triggered until the
next event loop iteration.
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()`][]:
```js
const util = require('util');
const setImmediatePromise = util.promisify(setImmediate);
setImmediatePromise('foobar').then((value) => {
// value === 'foobar' (passing values is optional)
// This is executed after all I/O callbacks.
});
// Or with async function
async function timerExample() {
console.log('Before I/O callbacks');
await setImmediatePromise();
console.log('After I/O callbacks');
}
timerExample();
```
### `setInterval(callback, delay[, ...args])`
<!-- YAML
added: v0.0.1
-->
* `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 [`clearInterval()`][]
2010-10-28 14:18:16 +02:00
Schedules repeated execution of `callback` every `delay` milliseconds.
2010-10-28 14:18:16 +02:00
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.
### `setTimeout(callback, delay[, ...args])`
<!-- YAML
added: v0.0.1
-->
* `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()`][]
2010-10-28 14:18:16 +02:00
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()`][]:
```js
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.
});
```
## Cancelling timers
The [`setImmediate()`][], [`setInterval()`][], and [`setTimeout()`][] methods
each return objects that represent the scheduled timers. These can be used to
cancel the timer and prevent it from triggering.
For the promisified variants of [`setImmediate()`][] and [`setTimeout()`][],
an [`AbortController`][] may be used to cancel the timer. When canceled, the
returned Promises will be rejected with an `'AbortError'`.
For `setImmediate()`:
```js
const util = require('util');
const setImmediatePromise = util.promisify(setImmediate);
const ac = new AbortController();
const signal = ac.signal;
setImmediatePromise('foobar', { signal })
.then(console.log)
.catch((err) => {
if (err.message === 'AbortError')
console.log('The immediate was aborted');
});
ac.abort();
```
For `setTimeout()`:
```js
const util = require('util');
const setTimeoutPromise = util.promisify(setTimeout);
const ac = new AbortController();
const signal = ac.signal;
setTimeoutPromise(1000, 'foobar', { signal })
.then(console.log)
.catch((err) => {
if (err.message === 'AbortError')
console.log('The timeout was aborted');
});
ac.abort();
```
### `clearImmediate(immediate)`
<!-- YAML
added: v0.9.1
-->
* `immediate` {Immediate} An `Immediate` object as returned by
[`setImmediate()`][].
Cancels an `Immediate` object created by [`setImmediate()`][].
### `clearInterval(timeout)`
<!-- YAML
added: v0.0.1
-->
* `timeout` {Timeout} A `Timeout` object as returned by [`setInterval()`][].
Cancels a `Timeout` object created by [`setInterval()`][].
### `clearTimeout(timeout)`
<!-- YAML
added: v0.0.1
-->
* `timeout` {Timeout} A `Timeout` object as returned by [`setTimeout()`][].
Cancels a `Timeout` object created by [`setTimeout()`][].
## Timers Promises API
> Stability: 1 - Experimental
The `timers/promises` API provides an alternative set of timer functions
that return `Promise` objects. The API is accessible via
`require('timers/promises')`.
```js
const timersPromises = require('timers/promises');
```
### `timersPromises.setTimeout(delay\[, value\[, options\]\])`
* `delay` {number} The number of milliseconds to wait before resolving the
`Promise`.
* `value` {any} A value with which the `Promise` is resolved.
* `options` {Object}
* `ref` {boolean} Set to `false` to indicate that the scheduled `Timeout`
should not require the Node.js event loop to remain active.
**Default**: `true`.
* `signal` {AbortSignal} An optional `AbortSignal` that can be used to
cancel the scheduled `Timeout`.
### `timersPromises.setImmediate(\[value\[, options\]\])`
* `value` {any} A value with which the `Promise` is resolved.
* `options` {Object}
* `ref` {boolean} Set to `false` to indicate that the scheduled `Immediate`
should not require the Node.js event loop to remain active.
**Default**: `true`.
* `signal` {AbortSignal} An optional `AbortSignal` that can be used to
cancel the scheduled `Immediate`.
[Event Loop]: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout
[`AbortController`]: globals.html#globals_class_abortcontroller
[`TypeError`]: errors.html#errors_class_typeerror
[`clearImmediate()`]: timers.html#timers_clearimmediate_immediate
[`clearInterval()`]: timers.html#timers_clearinterval_timeout
[`clearTimeout()`]: timers.html#timers_cleartimeout_timeout
[`setImmediate()`]: timers.html#timers_setimmediate_callback_args
[`setInterval()`]: timers.html#timers_setinterval_callback_delay_args
[`setTimeout()`]: timers.html#timers_settimeout_callback_delay_args
[`util.promisify()`]: util.html#util_util_promisify_original