Have you ever needed to stop your JavaScript code for a while before executing the next line of code? or, maybe sometimes you want to create a delay in loading an animation or slow down the rate at which data loads on the screen.
Unlike other programming languages like Python which has an inbuilt time module and sleep() function, Javascript doesn’t have its own sleep function. But, there are multiple ways to create a delay in javascript without blocking the flow of the entire program. In this blog, we’ll explore different methods to create a sleep() function in JavaScript.
Table of Contents:
Different Methods to Make sleep() Function in JavaScript
There are multiple methods to create a sleep() function in JavaScript and produce a delay in the code.
Method 1: Using Promises with setTimeout()
The most common and efficient way to create a sleep() function or produce a delay in the output is by using the javascript setTimeout() function and putting it inside a Promise.
Example:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
console.log("Hello, From IntelliPaat")
sleep(2000).then(() => console.log("Slept for 2 seconds"))
Output:
Explanation: In this example, we are making our sleep() function by using Promises and setTimeout() function. First, “Hello, From IntelliPaat” is printed in the console. And then, after 2 seconds, the next statement is printed.
Method 2: Using async/await with a sleep Function
async/await is also used to make a sleep() function in JavaScript with cleaner and more readable syntax.
Example:
async function testDelay(){
console.log("Welcome To Intellipaat");
await sleep(2000);
console.log("Learn JavaScript From Intellipaat");
}
function sleep(delayTime) {
return new Promise(resolve => setTimeout(resolve, delayTime));
}
testDelay()
Output:
Explanation: In this example, we are using async/await to produce a delay in the execution of one code after another. When testDelay() function is executed first “Welcome To Intellipaat” is printed then a 2-second delay is produced. After that, “Learn JavaScript From Intellipaat” is printed. This is a non-blocking approach means javascript still handles other processes.
Method 3: Using setInterval() for Repeated Delays
If you need repeated delays one after another, setInterval() is the best way to do so.
Example:
let count = 0;
const interval = setInterval(() => {
console.log(`Interval ${++count}`);
if (count === 5) clearInterval(interval);
}, 1000);
Output:
Explanation: setInterval() runs the function every 1 second. And clearInterval(interval) stops this after 5 repetitions.
Best Use Cases For Various Sleep Methods
Here are the best use cases for all those methods that are used to make sleep function in JavaScript:
Ways To Produce sleep() Methods | Best Use Cases |
setTimeout() | It helps in producing a time delay. |
Promises | It is the modern technique of producing delay that is used for async handling. |
async/await | It makes your code structured and more readable. |
setInterval() | It helps in producing multiple delays. |
Here are some tips that you have to remember when you are making sleep() function in javascript:
- You can use async/await to write clean code
- Never use blocking methods (like while loops) to create delays, as they freeze entire programs.
- If you have produced more delays, then prefer setInterval() as compared to setTimeout.
Conclusion
JavaScript doesn’t have a built-in sleep() function as other languages like Python have. But you can create the sleep() function by using setTimeout(), async/await, and setInterval. The best approach is to use async/await for writing cleaner and structured code. Also, using async/await does not block the execution of other processes. By understanding these techniques, you’re able to produce delays in your code and handle time-based operations smoothly.
What is the JavaScript Version of sleep() – FAQs
1. What is sleep() in javascript?
JavaScript doesn’t have a built-in sleep() function. But you can create your own sleep() function using setTimeout() or async/await
2. Is sleep() function measured in seconds?
JavaScript timers like setTimeout() and setInterval() measure time and accept parameters in milliseconds (1 second = 1000 milliseconds).
3. Can I use sleep() in synchronous JavaScript code?
No, Javascript is a single-threaded language and doesn’t support synchronous sleep.
4. Does JavaScript's sleep() method affect performance?
No, But only If you use non-blocking methods like setTimeout() to create sleep() function. Using blocking methods can freeze the browser or slow down execution.
5. What is the difference between sleep() and setTimeout()?
In javascript, sleep() is a custom function that you can create in javascript using different methods while, setTimeout() in-built function in javascript that schedules execution but doesn’t pass a function.