|
| 1 | +--- |
| 2 | +title: Timers in Node.js |
| 3 | +layout: docs.hbs |
| 4 | +--- |
| 5 | + |
| 6 | +# Timers in Node.js and beyond |
| 7 | + |
| 8 | +The Timers module in Node.js contains functions that execute code after a set |
| 9 | +period of time. Timers do not need to be imported via `require()`, since |
| 10 | +all the methods are available globally to emulate the browser JavaScript API. |
| 11 | +To fully understand when timer functions will be executed, it's a good idea to |
| 12 | +read up on the the Node.js |
| 13 | +[Event Loop](../topics/the-event-loop-timers-and-nexttick). |
| 14 | + |
| 15 | +## Controlling the Time Continuum with Node.js |
| 16 | + |
| 17 | +The Node.js API provides several ways of scheduling code to execute at |
| 18 | +some point after the present moment. The functions below may seem familiar, |
| 19 | +since they are available in most browsers, but Node.js actually provides |
| 20 | +its own implementation of these methods. Timers integrate very closely |
| 21 | +with the system, and despite the fact that the API mirrors the browser |
| 22 | +API, there are some differences in implementation. |
| 23 | + |
| 24 | +### "When I say so" Execution ~ *`setTimeout()`* |
| 25 | + |
| 26 | +`setTimeout()` can be used to schedule code execution after a designated |
| 27 | +amount of milliseconds. This function is similar to |
| 28 | +[`window.setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout) |
| 29 | +from the browser JavaScript API, however a string of code cannot be passed |
| 30 | +to be executed. |
| 31 | + |
| 32 | +`setTimeout()` accepts a function to execute as its first argument and the |
| 33 | +millisecond delay defined as a number as the second argument. Additional |
| 34 | +arguments may also be included and these will be passed on to the function. Here |
| 35 | +is an example of that: |
| 36 | + |
| 37 | +```js |
| 38 | +function myFunc (arg) { |
| 39 | + console.log('arg was => ' + arg); |
| 40 | +} |
| 41 | + |
| 42 | +setTimeout(myFunc, 1500, 'funky'); |
| 43 | +``` |
| 44 | + |
| 45 | +The above function `myFunc()` will execute as close to 1500 |
| 46 | +milliseconds (or 1.5 seconds) as possible due to the call of `setTimeout()`. |
| 47 | + |
| 48 | +The timeout interval that is set cannot be relied upon to execute after |
| 49 | +that *exact* number of milliseconds. This is because other executing code that |
| 50 | +blocks or holds onto the event loop will push the execution of the timeout |
| 51 | +back. The *only* guarantee is that the timeout will not execute *sooner* than |
| 52 | +the declared timeout interval. |
| 53 | + |
| 54 | +`setTimeout()` returns a `Timeout` object that can be used to reference the |
| 55 | +timeout that was set. This returned object can be used to cancel the timeout ( |
| 56 | +see `clearTimeout()` below) as well as change the execution behavior (see |
| 57 | +`unref()` below). |
| 58 | + |
| 59 | +### "Right after this" Execution ~ *`setImmediate()`* |
| 60 | + |
| 61 | +`setImmediate()` will execute code at the end of the current event loop cycle. |
| 62 | +This code will execute *after* any I/O operations in the current event loop and |
| 63 | +*before* any timers scheduled for the next event loop. This code execution |
| 64 | +could be thought of as happening "right after this", meaning any code following |
| 65 | +the `setImmediate()` function call will execute before the `setImmediate()` |
| 66 | +function argument. |
| 67 | + |
| 68 | +The first argument to `setImmediate()` will be the function to execute. Any |
| 69 | +subsequent arguments will be passed to the function when it is executed. |
| 70 | +Here's an example: |
| 71 | + |
| 72 | +```js |
| 73 | +console.log('before immediate'); |
| 74 | + |
| 75 | +setImmediate((arg) => { |
| 76 | + console.log(`executing immediate: ${arg}`); |
| 77 | +}, 'so immediate'); |
| 78 | + |
| 79 | +console.log('after immediate'); |
| 80 | +``` |
| 81 | + |
| 82 | +The above function passed to `setImmediate()` will execute after all runnable |
| 83 | +code has executed, and the console output will be: |
| 84 | + |
| 85 | +```shell |
| 86 | +before immediate |
| 87 | +after immediate |
| 88 | +executing immediate: so immediate |
| 89 | +``` |
| 90 | + |
| 91 | +`setImmediate()` returns and `Immediate` object, which can be used to cancel |
| 92 | +the scheduled immediate (see `clearImmediate()` below). |
| 93 | + |
| 94 | +Note: Don't get `setImmediate()` confused with `process.nextTick()`. There are |
| 95 | +some major ways they differ. The first is that `process.nextTick()` will run |
| 96 | +*before* any `Immediate`s that are set as well as before any scheduled I/O. |
| 97 | +The second is that `process.nextTick()` is non-clearable, meaning once |
| 98 | +code has been scheduled to execute with `process.nextTick()`, the execution |
| 99 | +cannot be stopped, just like with a normal function. Refer to [this guide](../topics/the-event-loop-timers-and-nexttick#processnexttick) |
| 100 | +to better understand the operation of `process.nextTick()`. |
| 101 | + |
| 102 | +### "Infinite Loop" Execution ~ *`setInterval()`* |
| 103 | + |
| 104 | +If there is a block of code that should execute multiple times, `setInterval()` |
| 105 | +can be used to execute that code. `setInterval()` takes a function |
| 106 | +argument that will run an infinite number of times with a given millisecond |
| 107 | +delay as the second argument. Just like `setTimeout()`, additional arguments |
| 108 | +can be added beyond the delay, and these will be passed on to the function call. |
| 109 | +Also like `setTimeout()`, the delay cannot be guaranteed because of operations |
| 110 | +that may hold on to the event loop, and therefore should be treated as an |
| 111 | +approximate delay. See the below example: |
| 112 | + |
| 113 | +```js |
| 114 | +function intervalFunc () { |
| 115 | + console.log('Cant stop me now!'); |
| 116 | +} |
| 117 | + |
| 118 | +setInterval(intervalFunc, 1500); |
| 119 | +``` |
| 120 | +In the above example, `intervalFunc()` will execute about every 1500 |
| 121 | +milliseconds, or 1.5 seconds, until it is stopped (see below). |
| 122 | + |
| 123 | +Just like `setTimeout()`, `setInterval()` also returns a `Timeout` object which |
| 124 | +can be used to reference and modify the interval that was set. |
| 125 | + |
| 126 | +## Clearing the Future |
| 127 | + |
| 128 | +What can be done if a `Timeout` or `Immediate` object needs to be cancelled? |
| 129 | +`setTimeout()`, `setImmediate()`, and `setInterval()` return a timer object |
| 130 | +that can be used to reference the set `Timeout` or `Immediate` object. |
| 131 | +By passing said object into the respective `clear` function, execution of |
| 132 | +that object will be halted completely. The respective functions are |
| 133 | +`clearTimeout()`, `clearImmediate()`, and `clearInterval()`. See the example |
| 134 | +below for an example of each: |
| 135 | + |
| 136 | +```js |
| 137 | +let timeoutObj = setTimeout(() => { |
| 138 | + console.log('timeout beyond time'); |
| 139 | +}, 1500); |
| 140 | + |
| 141 | +let immediateObj = setImmediate(() => { |
| 142 | + console.log('immediately executing immediate'); |
| 143 | +}); |
| 144 | + |
| 145 | +let intervalObj = setInterval(() => { |
| 146 | + console.log('interviewing the interval'); |
| 147 | +}, 500); |
| 148 | + |
| 149 | +clearTimeout(timeoutObj); |
| 150 | +clearImmediate(immediateObj); |
| 151 | +clearInterval(intervalObj); |
| 152 | +``` |
| 153 | + |
| 154 | +## Leaving Timeouts Behind |
| 155 | + |
| 156 | +Remember that `Timeout` objects are returned by `setTimeout` and `setInterval`. |
| 157 | +The `Timeout` object provides two functions intended to augment `Timeout` |
| 158 | +behavior with `unref()` and `ref()`. If there is a `Timeout` object scheduled |
| 159 | +using a `set` function, `unref()` can be called on that object. This will change |
| 160 | +the behavior slightly, and not call the `Timeout` object *if it is the last |
| 161 | +code to execute*. The `Timeout` object will not keep the process alive, waiting |
| 162 | +to execute. |
| 163 | + |
| 164 | +In similar fashion, a `Timeout` object that has had `unref()` called on it |
| 165 | +can remove that behavior by calling `ref()` on that same `Timeout` object, |
| 166 | +which will then ensure its execution. Be aware, however, that this does |
| 167 | +not *exactly* restore the initial behavior for performance reasons. See |
| 168 | +below for examples of both: |
| 169 | + |
| 170 | +```js |
| 171 | +let timerObj = setTimeout(() => { |
| 172 | + console.log('will i run?'); |
| 173 | +}); |
| 174 | + |
| 175 | +// if left alone, this statement will keep the above |
| 176 | +// timeout from running, since the timeout will be the only |
| 177 | +// thing keeping the program from exiting |
| 178 | +timerObj.unref(); |
| 179 | + |
| 180 | +// we can bring it back to life by calling ref() inside |
| 181 | +// an immediate |
| 182 | +setImmediate(() => { |
| 183 | + timerObj.ref(); |
| 184 | +}); |
| 185 | +``` |
| 186 | +## Further Down the Event Loop |
| 187 | + |
| 188 | +There's much more to the Event Loop and Timers than this guide |
| 189 | +has covered. To learn more about the internals of the Node.js |
| 190 | +Event Loop and how Timers operate during execution, check out |
| 191 | +this Node.js guide: [The Node.js Event Loop, Timers, and |
| 192 | +process.nextTick()](../topics/the-event-loop-timers-and-nexttick). |
0 commit comments