For quite a few years, when I needed my Node.js scripts to wait for some time, I used this promisified version of setTimeout
:
const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds))
Having that function, I can now say await sleep(1000)
to make my script wait a second.
Of course, I could also use util.promisify
for that:
import {promisify} from 'util' const sleep = promisify(setTimeout)
which is a bit shorter and has a very similar effect.
Recently, however, I learned that there is an even shorter way of defining an equivalent sleep
function:
import {setTimeout as sleep} from 'node:timers/promises'
and that’s it! Go check the docs (linked above) to learn about built-in promisified version of setInterval
and a few other utilities in the timers/promises
module.