What is javascript version of sleep()?


Sometimes we perform certain tasks in any language by maintaining a time delay. For instance, we are making a timer application that will update each second. In such cases, we wait for a second and update the second timer one by one. We also call this delay or sleep().In some other languages like Java, there is a sleep() function that is used to wait for some time. In this article, we shall see what is the equivalent method of sleep in javascript. Let us follow the syntaxes for delay generation

Syntax (Defining a function)

function sleep(t: the time in milliseconds) {
   return new Promise( resolve => setTimeout( resolve, t ));
}
// to apply delay
sleep(t)

Syntax (Single line solution)

await new Promise( r => setTimeout( r, t: the time in milliseconds));

Syntax (Another solution for single line definition)

const sleep = ms => new Promise(r => setTimeout(r, t: the time in
milliseconds));

// use delay like:
await sleep( <duration> );

Let us see one example, where we are printing lines every second. You cannot see any changes in the output of this article. You can see the effect by running it into your local system or any online HTML editor or save this code to the system and run on browser.

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { function sleep(time) { return new Promise(resolve => setTimeout(resolve, time)); } async function printAndWait() { for (let i = 0; i < 10; i++) { content += `Printing line after waiting ${i} seconds...` + "<br>"; opDiv.innerHTML = content await sleep(i * 1000); } content += 'Printing is completed' + "<br>";opDiv.innerHTML = content } printAndWait(); } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

In the last example, we have used the ‘await’ keyword. This ‘await’ keyword can only be executed inside the async function (Function where the async keyword is present before function definition), otherwise, we can use await at the top level of our script in an increasing number of environments. This await keyword only pauses the current async function. So that, it does not block the execution of the rest of the script. If we do want a blocking construct, we can use Atomics.wait() but this is browser-dependent, most browsers will not allow it on the browser's main thread

When we are using promises, we can use the .then() function to execute some code after waiting for some time. So from the sleep(), we are returning the promises and from the then() function the post-task can be executed. See the example for a better understanding. Here each line is printed after two seconds. The printing statement is present inside an anonymous function under asynchronous sleep method.

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { function sleep(time) { return new Promise(resolve => setTimeout(resolve, time)); } async function printAndWait() { for (let i = 0; i < 10; i++) { await sleep(2000).then(() => { content += `Printing line after waiting 2 seconds` + "<br>"; opDiv.innerHTML = content }); } content += 'Printing is completed' + "<br>";opDiv.innerHTML = content } printAndWait(); } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

Let’s make a countdown timer of 2 minutes using sleep.

Example (HTML)

<!DOCTYPE html> <html> <title>Online Javascript Editor</title> <head> </head> <body> <button onclick = startTimer()> Start Timer </button> <button onclick = resetTimer()> Restart Timer </button> <h2 id = "timerText" > 2:00 </h2> </body> <script> seconds = 120; var timerElem; function resetTimer(){ timerElem = document.getElementById( "timerText" ); timerElem.innerHTML = "2:00"; seconds = 120; } function startTimer(){ timerElem = document.getElementById( "timerText" ); countDown(); } function sleep( time ) { return new Promise( resolve => setTimeout( resolve, time )); } function setCurrentTime(){ var min = Math.floor( seconds / 60); var sec = seconds % 60; var secStr = String(sec).padStart(2, '0'); time = `${min}:${secStr}`; timerElem.innerHTML = time; seconds -= 1; } async function countDown(){ while(seconds >= 0){ await sleep(1000).then(setCurrentTime); } } </script> </body> </html>

In this example, we have created two buttons for starting and resetting the timer. It will reset the timer to 2 minutes. After each second it is decreasing the ‘seconds’ value by 1, then display it in m:ss format. This is one example of the sleep method in javascript.

Conclusion

Waiting for a little time is needed in some applications. Like other languages javascript also has time-dependent triggering functions which can be implemented by promises. As timer delay is asynchronous to the system, we must use async functions to execute them. And await keyword is used before calling the sleep() method. The codes are simply just to keep in mind the asynchronous programming skills while using delays or sleep.

Updated on: 23-Aug-2022

613 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements