(JS) sleep

Aug 08, 2023

While coding, there are often times when you need to wait for a specific duration.
For example, during tests, animations, etc…

A killer utility is needed!

sleep

Create your own utility using Promise.

const sleep = (ms: number) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

It uses setTimeout to wait for the given time (ms) and then calls resolve to fulfill the Promise.

lodash.delay

Since Promise is an ES5 syntax, it cannot operate in legacy browsers (IE) without additional help.
In such cases, it’s good to use a proven utility library like lodash.

yarn add lodash-es
yarn add -D @types/lodash-es

In modern environments, use lodash-es for tree shaking.

import { delay } from 'lodash-es';
 
delay(() => {
  console.log('sleep end');
}, 100);

If you look at the original code, it internally uses setTimeout as well, so there is no performance difference.