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('node: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 30<!-- YAML 31added: v11.0.0 32--> 33 34* Returns: {boolean} 35 36If true, the `Immediate` object will keep the Node.js event loop active. 37 38### `immediate.ref()` 39 40<!-- YAML 41added: v9.7.0 42--> 43 44* Returns: {Immediate} a reference to `immediate` 45 46When called, requests that the Node.js event loop _not_ exit so long as the 47`Immediate` is active. Calling `immediate.ref()` multiple times will have no 48effect. 49 50By default, all `Immediate` objects are "ref'ed", making it normally unnecessary 51to call `immediate.ref()` unless `immediate.unref()` had been called previously. 52 53### `immediate.unref()` 54 55<!-- YAML 56added: v9.7.0 57--> 58 59* Returns: {Immediate} a reference to `immediate` 60 61When called, the active `Immediate` object will not require the Node.js event 62loop to remain active. If there is no other activity keeping the event loop 63running, the process may exit before the `Immediate` object's callback is 64invoked. Calling `immediate.unref()` multiple times will have no effect. 65 66### `immediate[Symbol.dispose]()` 67 68<!-- YAML 69added: v18.18.0 70--> 71 72> Stability: 1 - Experimental 73 74Cancels the immediate. This is similar to calling `clearImmediate()`. 75 76## Class: `Timeout` 77 78This object is created internally and is returned from [`setTimeout()`][] and 79[`setInterval()`][]. It can be passed to either [`clearTimeout()`][] or 80[`clearInterval()`][] in order to cancel the scheduled actions. 81 82By default, when a timer is scheduled using either [`setTimeout()`][] or 83[`setInterval()`][], the Node.js event loop will continue running as long as the 84timer is active. Each of the `Timeout` objects returned by these functions 85export both `timeout.ref()` and `timeout.unref()` functions that can be used to 86control this default behavior. 87 88### `timeout.close()` 89 90<!-- YAML 91added: v0.9.1 92--> 93 94> Stability: 3 - Legacy: Use [`clearTimeout()`][] instead. 95 96* Returns: {Timeout} a reference to `timeout` 97 98Cancels the timeout. 99 100### `timeout.hasRef()` 101 102<!-- YAML 103added: v11.0.0 104--> 105 106* Returns: {boolean} 107 108If true, the `Timeout` object will keep the Node.js event loop active. 109 110### `timeout.ref()` 111 112<!-- YAML 113added: v0.9.1 114--> 115 116* Returns: {Timeout} a reference to `timeout` 117 118When called, requests that the Node.js event loop _not_ exit so long as the 119`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. 120 121By default, all `Timeout` objects are "ref'ed", making it normally unnecessary 122to call `timeout.ref()` unless `timeout.unref()` had been called previously. 123 124### `timeout.refresh()` 125 126<!-- YAML 127added: v10.2.0 128--> 129 130* Returns: {Timeout} a reference to `timeout` 131 132Sets the timer's start time to the current time, and reschedules the timer to 133call its callback at the previously specified duration adjusted to the current 134time. This is useful for refreshing a timer without allocating a new 135JavaScript object. 136 137Using this on a timer that has already called its callback will reactivate the 138timer. 139 140### `timeout.unref()` 141 142<!-- YAML 143added: v0.9.1 144--> 145 146* Returns: {Timeout} a reference to `timeout` 147 148When called, the active `Timeout` object will not require the Node.js event loop 149to remain active. If there is no other activity keeping the event loop running, 150the process may exit before the `Timeout` object's callback is invoked. Calling 151`timeout.unref()` multiple times will have no effect. 152 153### `timeout[Symbol.toPrimitive]()` 154 155<!-- YAML 156added: 157 - v14.9.0 158 - v12.19.0 159--> 160 161* Returns: {integer} a number that can be used to reference this `timeout` 162 163Coerce a `Timeout` to a primitive. The primitive can be used to 164clear the `Timeout`. The primitive can only be used in the 165same thread where the timeout was created. Therefore, to use it 166across [`worker_threads`][] it must first be passed to the correct 167thread. This allows enhanced compatibility with browser 168`setTimeout()` and `setInterval()` implementations. 169 170### `timeout[Symbol.dispose]()` 171 172<!-- YAML 173added: v18.18.0 174--> 175 176> Stability: 1 - Experimental 177 178Cancels the timeout. 179 180## Scheduling timers 181 182A timer in Node.js is an internal construct that calls a given function after 183a certain period of time. When a timer's function is called varies depending on 184which method was used to create the timer and what other work the Node.js 185event loop is doing. 186 187### `setImmediate(callback[, ...args])` 188 189<!-- YAML 190added: v0.9.1 191changes: 192 - version: v18.0.0 193 pr-url: https://github.com/nodejs/node/pull/41678 194 description: Passing an invalid callback to the `callback` argument 195 now throws `ERR_INVALID_ARG_TYPE` instead of 196 `ERR_INVALID_CALLBACK`. 197--> 198 199* `callback` {Function} The function to call at the end of this turn of 200 the Node.js [Event Loop][] 201* `...args` {any} Optional arguments to pass when the `callback` is called. 202* Returns: {Immediate} for use with [`clearImmediate()`][] 203 204Schedules the "immediate" execution of the `callback` after I/O events' 205callbacks. 206 207When multiple calls to `setImmediate()` are made, the `callback` functions are 208queued for execution in the order in which they are created. The entire callback 209queue is processed every event loop iteration. If an immediate timer is queued 210from inside an executing callback, that timer will not be triggered until the 211next event loop iteration. 212 213If `callback` is not a function, a [`TypeError`][] will be thrown. 214 215This method has a custom variant for promises that is available using 216[`timersPromises.setImmediate()`][]. 217 218### `setInterval(callback[, delay[, ...args]])` 219 220<!-- YAML 221added: v0.0.1 222changes: 223 - version: v18.0.0 224 pr-url: https://github.com/nodejs/node/pull/41678 225 description: Passing an invalid callback to the `callback` argument 226 now throws `ERR_INVALID_ARG_TYPE` instead of 227 `ERR_INVALID_CALLBACK`. 228--> 229 230* `callback` {Function} The function to call when the timer elapses. 231* `delay` {number} The number of milliseconds to wait before calling the 232 `callback`. **Default:** `1`. 233* `...args` {any} Optional arguments to pass when the `callback` is called. 234* Returns: {Timeout} for use with [`clearInterval()`][] 235 236Schedules repeated execution of `callback` every `delay` milliseconds. 237 238When `delay` is larger than `2147483647` or less than `1`, the `delay` will be 239set to `1`. Non-integer delays are truncated to an integer. 240 241If `callback` is not a function, a [`TypeError`][] will be thrown. 242 243This method has a custom variant for promises that is available using 244[`timersPromises.setInterval()`][]. 245 246### `setTimeout(callback[, delay[, ...args]])` 247 248<!-- YAML 249added: v0.0.1 250changes: 251 - version: v18.0.0 252 pr-url: https://github.com/nodejs/node/pull/41678 253 description: Passing an invalid callback to the `callback` argument 254 now throws `ERR_INVALID_ARG_TYPE` instead of 255 `ERR_INVALID_CALLBACK`. 256--> 257 258* `callback` {Function} The function to call when the timer elapses. 259* `delay` {number} The number of milliseconds to wait before calling the 260 `callback`. **Default:** `1`. 261* `...args` {any} Optional arguments to pass when the `callback` is called. 262* Returns: {Timeout} for use with [`clearTimeout()`][] 263 264Schedules execution of a one-time `callback` after `delay` milliseconds. 265 266The `callback` will likely not be invoked in precisely `delay` milliseconds. 267Node.js makes no guarantees about the exact timing of when callbacks will fire, 268nor of their ordering. The callback will be called as close as possible to the 269time specified. 270 271When `delay` is larger than `2147483647` or less than `1`, the `delay` 272will be set to `1`. Non-integer delays are truncated to an integer. 273 274If `callback` is not a function, a [`TypeError`][] will be thrown. 275 276This method has a custom variant for promises that is available using 277[`timersPromises.setTimeout()`][]. 278 279## Cancelling timers 280 281The [`setImmediate()`][], [`setInterval()`][], and [`setTimeout()`][] methods 282each return objects that represent the scheduled timers. These can be used to 283cancel the timer and prevent it from triggering. 284 285For the promisified variants of [`setImmediate()`][] and [`setTimeout()`][], 286an [`AbortController`][] may be used to cancel the timer. When canceled, the 287returned Promises will be rejected with an `'AbortError'`. 288 289For `setImmediate()`: 290 291```js 292const { setImmediate: setImmediatePromise } = require('node:timers/promises'); 293 294const ac = new AbortController(); 295const signal = ac.signal; 296 297setImmediatePromise('foobar', { signal }) 298 .then(console.log) 299 .catch((err) => { 300 if (err.name === 'AbortError') 301 console.error('The immediate was aborted'); 302 }); 303 304ac.abort(); 305``` 306 307For `setTimeout()`: 308 309```js 310const { setTimeout: setTimeoutPromise } = require('node:timers/promises'); 311 312const ac = new AbortController(); 313const signal = ac.signal; 314 315setTimeoutPromise(1000, 'foobar', { signal }) 316 .then(console.log) 317 .catch((err) => { 318 if (err.name === 'AbortError') 319 console.error('The timeout was aborted'); 320 }); 321 322ac.abort(); 323``` 324 325### `clearImmediate(immediate)` 326 327<!-- YAML 328added: v0.9.1 329--> 330 331* `immediate` {Immediate} An `Immediate` object as returned by 332 [`setImmediate()`][]. 333 334Cancels an `Immediate` object created by [`setImmediate()`][]. 335 336### `clearInterval(timeout)` 337 338<!-- YAML 339added: v0.0.1 340--> 341 342* `timeout` {Timeout|string|number} A `Timeout` object as returned by [`setInterval()`][] 343 or the [primitive][] of the `Timeout` object as a string or a number. 344 345Cancels a `Timeout` object created by [`setInterval()`][]. 346 347### `clearTimeout(timeout)` 348 349<!-- YAML 350added: v0.0.1 351--> 352 353* `timeout` {Timeout|string|number} A `Timeout` object as returned by [`setTimeout()`][] 354 or the [primitive][] of the `Timeout` object as a string or a number. 355 356Cancels a `Timeout` object created by [`setTimeout()`][]. 357 358## Timers Promises API 359 360<!-- YAML 361added: v15.0.0 362changes: 363 - version: v16.0.0 364 pr-url: https://github.com/nodejs/node/pull/38112 365 description: Graduated from experimental. 366--> 367 368The `timers/promises` API provides an alternative set of timer functions 369that return `Promise` objects. The API is accessible via 370`require('node:timers/promises')`. 371 372```mjs 373import { 374 setTimeout, 375 setImmediate, 376 setInterval, 377} from 'timers/promises'; 378``` 379 380```cjs 381const { 382 setTimeout, 383 setImmediate, 384 setInterval, 385} = require('node:timers/promises'); 386``` 387 388### `timersPromises.setTimeout([delay[, value[, options]]])` 389 390<!-- YAML 391added: v15.0.0 392--> 393 394* `delay` {number} The number of milliseconds to wait before fulfilling the 395 promise. **Default:** `1`. 396* `value` {any} A value with which the promise is fulfilled. 397* `options` {Object} 398 * `ref` {boolean} Set to `false` to indicate that the scheduled `Timeout` 399 should not require the Node.js event loop to remain active. 400 **Default:** `true`. 401 * `signal` {AbortSignal} An optional `AbortSignal` that can be used to 402 cancel the scheduled `Timeout`. 403 404```mjs 405import { 406 setTimeout, 407} from 'timers/promises'; 408 409const res = await setTimeout(100, 'result'); 410 411console.log(res); // Prints 'result' 412``` 413 414```cjs 415const { 416 setTimeout, 417} = require('node:timers/promises'); 418 419setTimeout(100, 'result').then((res) => { 420 console.log(res); // Prints 'result' 421}); 422``` 423 424### `timersPromises.setImmediate([value[, options]])` 425 426<!-- YAML 427added: v15.0.0 428--> 429 430* `value` {any} A value with which the promise is fulfilled. 431* `options` {Object} 432 * `ref` {boolean} Set to `false` to indicate that the scheduled `Immediate` 433 should not require the Node.js event loop to remain active. 434 **Default:** `true`. 435 * `signal` {AbortSignal} An optional `AbortSignal` that can be used to 436 cancel the scheduled `Immediate`. 437 438```mjs 439import { 440 setImmediate, 441} from 'timers/promises'; 442 443const res = await setImmediate('result'); 444 445console.log(res); // Prints 'result' 446``` 447 448```cjs 449const { 450 setImmediate, 451} = require('node:timers/promises'); 452 453setImmediate('result').then((res) => { 454 console.log(res); // Prints 'result' 455}); 456``` 457 458### `timersPromises.setInterval([delay[, value[, options]]])` 459 460<!-- YAML 461added: v15.9.0 462--> 463 464Returns an async iterator that generates values in an interval of `delay` ms. 465If `ref` is `true`, you need to call `next()` of async iterator explicitly 466or implicitly to keep the event loop alive. 467 468* `delay` {number} The number of milliseconds to wait between iterations. 469 **Default:** `1`. 470* `value` {any} A value with which the iterator returns. 471* `options` {Object} 472 * `ref` {boolean} Set to `false` to indicate that the scheduled `Timeout` 473 between iterations should not require the Node.js event loop to 474 remain active. 475 **Default:** `true`. 476 * `signal` {AbortSignal} An optional `AbortSignal` that can be used to 477 cancel the scheduled `Timeout` between operations. 478 479```mjs 480import { 481 setInterval, 482} from 'timers/promises'; 483 484const interval = 100; 485for await (const startTime of setInterval(interval, Date.now())) { 486 const now = Date.now(); 487 console.log(now); 488 if ((now - startTime) > 1000) 489 break; 490} 491console.log(Date.now()); 492``` 493 494```cjs 495const { 496 setInterval, 497} = require('node:timers/promises'); 498const interval = 100; 499 500(async function() { 501 for await (const startTime of setInterval(interval, Date.now())) { 502 const now = Date.now(); 503 console.log(now); 504 if ((now - startTime) > 1000) 505 break; 506 } 507 console.log(Date.now()); 508})(); 509``` 510 511### `timersPromises.scheduler.wait(delay[, options])` 512 513<!-- YAML 514added: 515 - v17.3.0 516 - v16.14.0 517--> 518 519> Stability: 1 - Experimental 520 521* `delay` {number} The number of milliseconds to wait before resolving the 522 promise. 523* `options` {Object} 524 * `signal` {AbortSignal} An optional `AbortSignal` that can be used to 525 cancel waiting. 526* Returns: {Promise} 527 528An experimental API defined by the [Scheduling APIs][] draft specification 529being developed as a standard Web Platform API. 530 531Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent 532to calling `timersPromises.setTimeout(delay, undefined, options)` except that 533the `ref` option is not supported. 534 535```mjs 536import { scheduler } from 'node:timers/promises'; 537 538await scheduler.wait(1000); // Wait one second before continuing 539``` 540 541### `timersPromises.scheduler.yield()` 542 543<!-- YAML 544added: 545 - v17.3.0 546 - v16.14.0 547--> 548 549> Stability: 1 - Experimental 550 551* Returns: {Promise} 552 553An experimental API defined by the [Scheduling APIs][] draft specification 554being developed as a standard Web Platform API. 555 556Calling `timersPromises.scheduler.yield()` is equivalent to calling 557`timersPromises.setImmediate()` with no arguments. 558 559[Event Loop]: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout 560[Scheduling APIs]: https://github.com/WICG/scheduling-apis 561[`AbortController`]: globals.md#class-abortcontroller 562[`TypeError`]: errors.md#class-typeerror 563[`clearImmediate()`]: #clearimmediateimmediate 564[`clearInterval()`]: #clearintervaltimeout 565[`clearTimeout()`]: #cleartimeouttimeout 566[`setImmediate()`]: #setimmediatecallback-args 567[`setInterval()`]: #setintervalcallback-delay-args 568[`setTimeout()`]: #settimeoutcallback-delay-args 569[`timersPromises.setImmediate()`]: #timerspromisessetimmediatevalue-options 570[`timersPromises.setInterval()`]: #timerspromisessetintervaldelay-value-options 571[`timersPromises.setTimeout()`]: #timerspromisessettimeoutdelay-value-options 572[`worker_threads`]: worker_threads.md 573[primitive]: #timeoutsymboltoprimitive 574