Categories
JavaScript Answers

How to use setTimeout synchronously in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *