How to use setTimeout synchronously in JavaScript?

Sometimes, we want to use setTimeout synchronously in JavaScript.

In this article, we’ll look at how to use setTimeout synchronously in JavaScript.

How to use setTimeout synchronously in JavaScript?

To use setTimeout synchronously in JavaScript, we wrap setTimeout in a promise.

For instance, we write

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

const demo = async () => {
  console.log("this should be the first one");
  await sleep(5000);
  console.log("this should be the second one");
};

demo();

to define the sleep function that returns a promise that calls setTimeout which calls resolve after ms milliseconds.

Then we define the demo function that calls console.log, sleep and console.log again.

We should see the first line logged, and then the 2nd line logged 5 seconds after.

Conclusion

To use setTimeout synchronously in JavaScript, we wrap setTimeout in a promise.