Ever found yourself needing to pause a process in your Node.js application? Maybe for testing or just to let something else catch up? The go-to method has always been the trusty setTimeout
wrapped in a promise. It’s simple and gets the job done:
await new Promise(resolve => setTimeout(resolve, 1000));
This snippet waits for a second before resolving to undefined
. It’s straightforward, but did you know there’s a more elegant way?
Recently, I stumbled upon Node's built-in API that does the same thing, but with a bit more flair. Check this out:
import { setTimeout } from 'node:timers/promises';
const res = await setTimeout(1000, 'result');
console.log(res); // Prints 'result'
This method not only waits for a second but also returns a specified value, in this case, 'result'
. It’s a neat little upgrade from the classic method.
The new API also allows for some optional parameters through an interface:
interface Options {
ref?: boolean | undefined;
signal?: AbortSignal | undefined;
}
ref
OptionOne of the cool things is the ref
option. By setting ref
to false
, the Node.js event loop can exit if there’s nothing else to do, even if the timeout is still pending. This is super handy for background tasks that shouldn’t block the main execution.
signal
OptionYou can also use an AbortSignal
to cancel the timeout if needed. This adds a layer of control, allowing you to abort the timer if circumstances change.
Node.js now offers a built-in API for delaying processes with setTimeout
from node:timers/promises
. It’s a cleaner alternative to the classic promise-wrapped setTimeout
, with added options like ref
and signal
for more control over the event loop and timer cancellation.