Artboard 16Google Sheets iconSwift icon
Published at
Updated at
Reading time
1min

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 {
  setTimeout,
} 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 15 days ago.

Related Topics

Related Articles