• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Timers
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/timers.js -->
8
9The `timer` module exposes a global API for scheduling functions to
10be called at some future period of time. Because the timer functions are
11globals, there is no need to call `require('timers')` to use the API.
12
13The timer functions within Node.js implement a similar API as the timers API
14provided by Web Browsers but use a different internal implementation that is
15built around the Node.js [Event Loop][].
16
17## Class: `Immediate`
18
19This object is created internally and is returned from [`setImmediate()`][]. It
20can be passed to [`clearImmediate()`][] in order to cancel the scheduled
21actions.
22
23By default, when an immediate is scheduled, the Node.js event loop will continue
24running as long as the immediate is active. The `Immediate` object returned by
25[`setImmediate()`][] exports both `immediate.ref()` and `immediate.unref()`
26functions that can be used to control this default behavior.
27
28### `immediate.hasRef()`
29<!-- YAML
30added: v11.0.0
31-->
32
33* Returns: {boolean}
34
35If true, the `Immediate` object will keep the Node.js event loop active.
36
37### `immediate.ref()`
38<!-- YAML
39added: v9.7.0
40-->
41
42* Returns: {Immediate} a reference to `immediate`
43
44When called, requests that the Node.js event loop *not* exit so long as the
45`Immediate` is active. Calling `immediate.ref()` multiple times will have no
46effect.
47
48By default, all `Immediate` objects are "ref'ed", making it normally unnecessary
49to call `immediate.ref()` unless `immediate.unref()` had been called previously.
50
51### `immediate.unref()`
52<!-- YAML
53added: v9.7.0
54-->
55
56* Returns: {Immediate} a reference to `immediate`
57
58When called, the active `Immediate` object will not require the Node.js event
59loop to remain active. If there is no other activity keeping the event loop
60running, the process may exit before the `Immediate` object's callback is
61invoked. Calling `immediate.unref()` multiple times will have no effect.
62
63## Class: `Timeout`
64
65This object is created internally and is returned from [`setTimeout()`][] and
66[`setInterval()`][]. It can be passed to either [`clearTimeout()`][] or
67[`clearInterval()`][] in order to cancel the scheduled actions.
68
69By default, when a timer is scheduled using either [`setTimeout()`][] or
70[`setInterval()`][], the Node.js event loop will continue running as long as the
71timer is active. Each of the `Timeout` objects returned by these functions
72export both `timeout.ref()` and `timeout.unref()` functions that can be used to
73control this default behavior.
74
75### `timeout.hasRef()`
76<!-- YAML
77added: v11.0.0
78-->
79
80* Returns: {boolean}
81
82If true, the `Timeout` object will keep the Node.js event loop active.
83
84### `timeout.ref()`
85<!-- YAML
86added: v0.9.1
87-->
88
89* Returns: {Timeout} a reference to `timeout`
90
91When called, requests that the Node.js event loop *not* exit so long as the
92`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect.
93
94By default, all `Timeout` objects are "ref'ed", making it normally unnecessary
95to call `timeout.ref()` unless `timeout.unref()` had been called previously.
96
97### `timeout.refresh()`
98<!-- YAML
99added: v10.2.0
100-->
101
102* Returns: {Timeout} a reference to `timeout`
103
104Sets the timer's start time to the current time, and reschedules the timer to
105call its callback at the previously specified duration adjusted to the current
106time. This is useful for refreshing a timer without allocating a new
107JavaScript object.
108
109Using this on a timer that has already called its callback will reactivate the
110timer.
111
112### `timeout.unref()`
113<!-- YAML
114added: v0.9.1
115-->
116
117* Returns: {Timeout} a reference to `timeout`
118
119When called, the active `Timeout` object will not require the Node.js event loop
120to remain active. If there is no other activity keeping the event loop running,
121the process may exit before the `Timeout` object's callback is invoked. Calling
122`timeout.unref()` multiple times will have no effect.
123
124Calling `timeout.unref()` creates an internal timer that will wake the Node.js
125event loop. Creating too many of these can adversely impact performance
126of the Node.js application.
127
128### `timeout[Symbol.toPrimitive]()`
129<!-- YAML
130added: v14.9.0
131-->
132
133* Returns: {integer} a number that can be used to reference this `timeout`
134
135Coerce a `Timeout` to a primitive. The primitive can be used to
136clear the `Timeout`. The primitive can only be used in the
137same thread where the timeout was created. Therefore, to use it
138across [`worker_threads`][] it must first be passed to the correct
139thread. This allows enhanced compatibility with browser
140`setTimeout()` and `setInterval()` implementations.
141
142## Scheduling timers
143
144A timer in Node.js is an internal construct that calls a given function after
145a certain period of time. When a timer's function is called varies depending on
146which method was used to create the timer and what other work the Node.js
147event loop is doing.
148
149### `setImmediate(callback[, ...args])`
150<!-- YAML
151added: v0.9.1
152-->
153
154* `callback` {Function} The function to call at the end of this turn of
155  the Node.js [Event Loop][]
156* `...args` {any} Optional arguments to pass when the `callback` is called.
157* Returns: {Immediate} for use with [`clearImmediate()`][]
158
159Schedules the "immediate" execution of the `callback` after I/O events'
160callbacks.
161
162When multiple calls to `setImmediate()` are made, the `callback` functions are
163queued for execution in the order in which they are created. The entire callback
164queue is processed every event loop iteration. If an immediate timer is queued
165from inside an executing callback, that timer will not be triggered until the
166next event loop iteration.
167
168If `callback` is not a function, a [`TypeError`][] will be thrown.
169
170This method has a custom variant for promises that is available using
171[`util.promisify()`][]:
172
173```js
174const util = require('util');
175const setImmediatePromise = util.promisify(setImmediate);
176
177setImmediatePromise('foobar').then((value) => {
178  // value === 'foobar' (passing values is optional)
179  // This is executed after all I/O callbacks.
180});
181
182// Or with async function
183async function timerExample() {
184  console.log('Before I/O callbacks');
185  await setImmediatePromise();
186  console.log('After I/O callbacks');
187}
188timerExample();
189```
190
191### `setInterval(callback[, delay[, ...args]])`
192<!-- YAML
193added: v0.0.1
194-->
195
196* `callback` {Function} The function to call when the timer elapses.
197* `delay` {number} The number of milliseconds to wait before calling the
198  `callback`. **Default**: `1`.
199* `...args` {any} Optional arguments to pass when the `callback` is called.
200* Returns: {Timeout} for use with [`clearInterval()`][]
201
202Schedules repeated execution of `callback` every `delay` milliseconds.
203
204When `delay` is larger than `2147483647` or less than `1`, the `delay` will be
205set to `1`. Non-integer delays are truncated to an integer.
206
207If `callback` is not a function, a [`TypeError`][] will be thrown.
208
209### `setTimeout(callback[, delay[, ...args]])`
210<!-- YAML
211added: v0.0.1
212-->
213
214* `callback` {Function} The function to call when the timer elapses.
215* `delay` {number} The number of milliseconds to wait before calling the
216  `callback`. **Default**: `1`.
217* `...args` {any} Optional arguments to pass when the `callback` is called.
218* Returns: {Timeout} for use with [`clearTimeout()`][]
219
220Schedules execution of a one-time `callback` after `delay` milliseconds.
221
222The `callback` will likely not be invoked in precisely `delay` milliseconds.
223Node.js makes no guarantees about the exact timing of when callbacks will fire,
224nor of their ordering. The callback will be called as close as possible to the
225time specified.
226
227When `delay` is larger than `2147483647` or less than `1`, the `delay`
228will be set to `1`. Non-integer delays are truncated to an integer.
229
230If `callback` is not a function, a [`TypeError`][] will be thrown.
231
232This method has a custom variant for promises that is available using
233[`util.promisify()`][]:
234
235```js
236const util = require('util');
237const setTimeoutPromise = util.promisify(setTimeout);
238
239setTimeoutPromise(40, 'foobar').then((value) => {
240  // value === 'foobar' (passing values is optional)
241  // This is executed after about 40 milliseconds.
242});
243```
244
245## Cancelling timers
246
247The [`setImmediate()`][], [`setInterval()`][], and [`setTimeout()`][] methods
248each return objects that represent the scheduled timers. These can be used to
249cancel the timer and prevent it from triggering.
250
251For the promisified variants of [`setImmediate()`][] and [`setTimeout()`][],
252an [`AbortController`][] may be used to cancel the timer. When canceled, the
253returned Promises will be rejected with an `'AbortError'`.
254
255For `setImmediate()`:
256
257```js
258const util = require('util');
259const setImmediatePromise = util.promisify(setImmediate);
260
261const ac = new AbortController();
262const signal = ac.signal;
263
264setImmediatePromise('foobar', { signal })
265  .then(console.log)
266  .catch((err) => {
267    if (err.name === 'AbortError')
268      console.log('The immediate was aborted');
269  });
270
271ac.abort();
272```
273
274For `setTimeout()`:
275
276```js
277const util = require('util');
278const setTimeoutPromise = util.promisify(setTimeout);
279
280const ac = new AbortController();
281const signal = ac.signal;
282
283setTimeoutPromise(1000, 'foobar', { signal })
284  .then(console.log)
285  .catch((err) => {
286    if (err.name === 'AbortError')
287      console.log('The timeout was aborted');
288  });
289
290ac.abort();
291```
292
293### `clearImmediate(immediate)`
294<!-- YAML
295added: v0.9.1
296-->
297
298* `immediate` {Immediate} An `Immediate` object as returned by
299  [`setImmediate()`][].
300
301Cancels an `Immediate` object created by [`setImmediate()`][].
302
303### `clearInterval(timeout)`
304<!-- YAML
305added: v0.0.1
306-->
307
308* `timeout` {Timeout|string|number} A `Timeout` object as returned by [`setInterval()`][]
309  or the [primitive][] of the `Timeout` object as a string or a number.
310
311Cancels a `Timeout` object created by [`setInterval()`][].
312
313### `clearTimeout(timeout)`
314<!-- YAML
315added: v0.0.1
316-->
317
318* `timeout` {Timeout|string|number} A `Timeout` object as returned by [`setTimeout()`][]
319  or the [primitive][] of the `Timeout` object as a string or a number.
320
321Cancels a `Timeout` object created by [`setTimeout()`][].
322
323[Event Loop]: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout
324[`AbortController`]: globals.md#globals_class_abortcontroller
325[`TypeError`]: errors.md#errors_class_typeerror
326[`clearImmediate()`]: #timers_clearimmediate_immediate
327[`clearInterval()`]: #timers_clearinterval_timeout
328[`clearTimeout()`]: #timers_cleartimeout_timeout
329[`setImmediate()`]: #timers_setimmediate_callback_args
330[`setInterval()`]: #timers_setinterval_callback_delay_args
331[`setTimeout()`]: #timers_settimeout_callback_delay_args
332[`util.promisify()`]: util.md#util_util_promisify_original
333[`worker_threads`]: worker_threads.md
334[primitive]: #timers_timeout_symbol_toprimitive
335