In this article, we will get to know the meaning of sleep or wait in JavaScript programming.
In various programming languages, including JavaScript, the Sleep function is used to specify a time delay (usually in milliseconds or seconds) for which the program should pause before continuing with the next instruction. It’s a way to introduce a delay or pause in the execution flow.
This can be useful for various purposes such as timing, synchronization, or controlling the flow of execution:
- Synchronization: In multi-threaded programming, sleep can be used to synchronize different threads, ensuring that they do not interfere with each other’s operations.
- Throttling: Sleep can be used to limit the rate of various operations like API calls to prevent API limit from getting exhausted and giving the “too many requests” error.
- Controlling Flow: In several cases, we may need to control the flow of our code execution, pausing it for a specific duration before proceeding to the next step. This can be useful for animations, timed events, or coordinating actions sequentially.
How to Sleep or Wait in JavaScript?
In JavaScript, there is no inbuilt method to add sleep to our program rather, it can be achieved using a custom function or asynchronous code or setTimeout() function.
1) Achieving Sleep Without async
We can add sleep to our program by making a custom function. Here’s an example:
function sleep(milliseconds) { // Get the current timestamp in milliseconds const start = new Date().getTime(); // Loop until the specified time has elapsed while (new Date().getTime() - start < milliseconds); } // Display a message before the sleep console.log("Before sleep"); // Call the sleep function to pause execution for 3 seconds (3000 milliseconds) sleep(3000); // Display a message after the sleep console.log("After sleep");
In the above example, as our program starts, “Before sleep” is printed in our output window, and after that, “After sleep” is printed in our output window after a delay of 3000 milliseconds or, we can say 3 seconds.
This delay of 3 seconds is possible because we are calling the sleep function and passing 3000 (which is the expected delay we want) as a parameter in it.
In the sleep function, we are saving current time when the function is called in the start variable, and then we have called a blocking while loop which will end when the difference between our current time and start time will be equal to the delay that we passed as a parameter.
This method uses a loop that continuously checks the current time, which blocks the execution of other code. Thus, this method is generally not recommended for use in web applications where responsiveness is crucial.
2) Using the setTimeout() Function
We can introduce sleep in our program by using the setTimeout function of javascript, which takes two parameters – a function and a delay time.
The function passed inside the setTimeout function gets executed after the delay time has elapsed.
Here is a simple example:
// Display a message indicating the start of the code execution console.log("Start"); // Set a timeout to execute a function after 3000 milliseconds (3 seconds) setTimeout(function() { // Display a message after the timeout console.log("Hello"); }, 3000); // Display a message indicating the end of the code execution console.log("End");
This code will first print “Start” in the output window and then, after a delay of 3 seconds, callback passed inside the setTImeout function will get executed and “Hello” will get printed in the output window and after that “End” will get printed.
Output:
Start
Hello → this will get printed after a delay of 3 seconds
End
How do we calculate the time we need to pass?
In setTimeout, we need to pass the time we want our program to sleep in milliseconds which can be calculated very easily by just converting our delay time into seconds and then multiplying it with 1000 to get time in milliseconds.
1 hour = 1 X 60 minutes = 60 X 60 seconds = 60 X 60 X 1000 milliseconds = 36,00,000 ms
Introducing sleep with a 1-minute delay
If we want to introduce a sleep of 1 minute in our program, then we need to convert 1 minute to milliseconds and then pass it inside the setTimeout function as a parameter.
1 minute = 60 seconds = 60 X 1000 milliseconds = 60,000 milliseconds
Here is a demonstration of the above example with a delay of 1 minute:
// Display a message indicating the start of the code execution console.log("Start"); // Set a timeout to execute a function after 60000 milliseconds (60 seconds or 1 minute) setTimeout(function() { // Display a message after the timeout console.log("Hello"); }, 60000); // Display a message indicating the end of the code execution console.log("End");
Output:
Start
Hello → this will get printed after a delay of 60000 milliseconds(1 minute)
End
3) Achieving sleep using async/await
We can use the useTimeout() function to add sleep in our program which uses asynchronous code and avoids blocking of the main thread.
For example:
function sleepAsync(milliseconds) { // Return a Promise that resolves after the specified time return new Promise(resolve => setTimeout(resolve, milliseconds)); } async function favTutor() { // Display a message before the asynchronous sleep console.log("Before sleep"); // Sleep for 3 seconds await sleepAsync(3000); // Display a message after the asynchronous sleep console.log("After sleep"); } //calling the asynchronous function favTutor favTutor();
Here, our entry function i.e. FavTutor, is being called, which first prints “Before sleep” in the output window, and then it awaits the sleepAsync function in which we have passed 3000 as a parameter that defines time in milliseconds.
sleepAsync function returns a promise that is resolved after the delay of 3000 milliseconds because of the setTimeout function.
setTimeout is a predefined function in JavaScript that takes another function or a piece of code along with time in milliseconds. The piece of code or function gets executed after the specified time has elapsed.
Therefore, this method of using the setTimeout function to introduce sleep in our program is very commonly used and is preferred over the previous method as it does not block the execution of the main thread.
Conclusion
We have thoroughly explored sleep in JavaScript. Now you can also refer to C++ sleep Function with syntax & examples.