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