How to add delay between actions in JavaScript?

Sometimes, we want to add delay between actions in JavaScript.

In this article, we’ll look at how to add delay between actions in JavaScript.

How to add delay between actions in JavaScript?

To add delay between actions in JavaScript, we can create a function that returns a promise that delays the script by the time we want.

For instance, we write

const sleep = (ms) => {
  return new Promise((res) => setTimeout(res, ms));
};

const myAsyncFunc = async () => {
  console.log("Sleeping");
  await sleep(3000);
  console.log("Done");
};

myAsyncFunc();

to create the sleep function that returns a promise that calls setTimeout to call res in ms milliseconds.

Then we use await sleep in myAsyncFunc to delay the execution of the function by 3000 milliseconds.

Conclusion

To add delay between actions in JavaScript, we can create a function that returns a promise that delays the script by the time we want.