Published at
Updated at
Reading time

When writing Node.js automation/build scripts, I occasionally need "sleep" functionality to wait for other tasks to finish. It's not great to implement "sleeps and waits", but sometimes there's no other way than waiting for another system to finish what it's doing.

I often use the following snippet in a Node.js module script. ๐Ÿ‘‡

// File: index.mjs

const sleep = (time) => {
  return new Promise((resolve) => {
    setTimeout(resolve, time);

// do something
await sleep(5000);
// do something else

There's nothing particularly wrong with this approach, but I'm very pleased to see that promises-based timer functions are available in Node.js 16 via timers/promises now.

// File: index.mjs

import {
} from 'timers/promises';

// do something
await setTimeout(5000);
// do something else

Less code is always better code! ๐Ÿ‘

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 8 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles