How to Sleep and Wait in JavaScript
Table of Contents
You can pause the execution of a JavaScript function for a specified amount of time by taking advantage of the timeouts feature of the JavaScript engine and promises.
Timeouts allow you to run code after a certain amount of time has passed.
We can make the timeout resolve a promise after a specified amount of time has passed, thereby allowing us to continue the execution of the code after the timeout has passed.
First, let's create a promise that resolves after a timeout is passed.
JAVASCRIPTconst sleep = (duration) => {
return new Promise(resolve => setTimeout(resolve, duration));
}
From here, you can then call this function and pass the then
method a callback function that will be executed after the specified amount of time.
JAVASCRIPTsleep(1000).then(() => {
console.log("I waited 1 second");
})
If you don't want to use then()
, you can use the more modern await
syntax.
JAVASCRIPTconst sleep = (duration) => {
return new Promise(resolve => setTimeout(resolve, duration));
}
const main = async () => {
await sleep(1000)
console.log("I waited 1 second");
}
You can even define sleep
in a single line of code:
JAVASCRIPTconst sleep = (duration) => new Promise(resolve => setTimeout(resolve, duration));
Now that's some beautiful code!
Conclusion
In this post, we've covered how you can combine timeouts and promises to support sleeping for a specified amount of time.
You can use this in your code to make JavaScript wait for a certain amount of time before continuing.
Hopefully, you've found this post useful and have enjoyed reading it.
Happy coding!
- Getting Started with TypeScript
- Getting Started with Solid
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js