Sometimes, we want to add synchronous delay in code execution with JavaScript.
In this article, we’ll look at how to add synchronous delay in code execution with JavaScript.
How to add synchronous delay in code execution with JavaScript?
To add synchronous delay in code execution with JavaScript, we use a promise.
For instance, we write
const asyncWait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
(async () => {
console.log("one");
await asyncWait(5000);
console.log("two");
})();
to create the asyncWait function that returns a promise that calls setTiimeout with ms milliseconds.
The promise is settled after resolve is called after ms milliseconds.
Then we call it in the async function with await to wait for the promise to finish before calling the 2nd console.log.
Conclusion
To add synchronous delay in code execution with JavaScript, we use a promise.