Table of Contents
Sleeping can be a useful feature to implement in your code.
It can be used to wait for a certain amount of time before executing the next line of code.
In this article, we will learn how to implement a sleep function in JavaScript.
How to implement a function to sleep in JavaScript
The issue with sleep functions in JavaScript is that they are not blocking.
This means that the code will continue to execute while the sleep function is running.
One way to implement a sleep function is to use the setTimeout function in conjunction with a Promise.
The setTimeout function takes a callback function as its first argument and a time in milliseconds as its second argument.
Let's see an example:
JAVASCRIPTconst sleep = (milliseconds) => {
    return new Promise(resolve => setTimeout(resolve, milliseconds))
}
console.log("Hello");
sleep(1000).then(() => {
    console.log("World");
});
This will print Hello to the console immediately and World after 1 second after the promise is resolved.
This works but it is not very elegant, especially because you have to use the then function and nest the code inside of it.
Another way to implement a sleep function is to use the async and await keywords.
Let's see an example using async/await:
JAVASCRIPTconst sleep = async (milliseconds) => {
    return new Promise(resolve => setTimeout(resolve, milliseconds))
}
console.log("Hello");
await sleep(1000);
console.log("World");
Like before this will also print Hello immediately, then after a second it will print World.
This is a lot cleaner than the previous example while keeping the functionality the same.
Conclusion
In this post, we learned how to implement a sleep function in JavaScript.
For the best results, use the async/await syntax with the Promise object.
Thanks for reading!
 Getting Started with Solid Getting Started with Solid
 Getting Started with Express Getting Started with Express
 Getting Started with Electron Getting Started with Electron
 Git Tutorial: Learn how to use Version Control Git Tutorial: Learn how to use Version Control
 Getting Started with Deno Getting Started with Deno
 How to deploy a MySQL Server using Docker How to deploy a MySQL Server using Docker
 How to deploy a Node app using Docker How to deploy a Node app using Docker
 Using Puppeteer and Jest for End-to-End Testing Using Puppeteer and Jest for End-to-End Testing
 How to Scrape the Web using Node.js and Puppeteer How to Scrape the Web using Node.js and Puppeteer
 Learn how to build a Slack Bot using Node.js Learn how to build a Slack Bot using Node.js
 Building a Real-Time Note-Taking App with Vue and Firebase Building a Real-Time Note-Taking App with Vue and Firebase
 Setting Up Stylus CSS Preprocessor Setting Up Stylus CSS Preprocessor
