DEV Community

François
François

Posted on • Originally published at blog.lepape.me on

Good bye sleep() and delay() with NodeJS, hello setTimeout()

Stop to use home-made utilities sleep() and delay(), and use the native nodeJS timers API: setTimeout().

I have seen and added many times in nodeJS codebase the following snippet:

const sleep = (ms) =>
  new Promise((resolve) => setTimeout(resolve, ms));
Enter fullscreen mode Exit fullscreen mode

Well, today I learned that nodeJS has a native API for that: setTimeout().

// https://nodejs.org/api/timers.html#timerspromisessettimeoutdelay-value-options
import { setTimeout } from 'node:timers/promises';

await setTimeout(2000); // sleep 2s
Enter fullscreen mode Exit fullscreen mode

So time to stop to use home-made utilities sleep() and delay(), and use the native nodeJS timers API!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay