Logo

dev-resources.site

for different kinds of informations.

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

Published at
11/27/2023
Categories
node
Author
François
Categories
1 categories in total
node
open
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));

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

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

Featured ones: