Introduction to Javascript Sleep
Many programming languages provide the functionality to make a particular thread sleep or pause for some period. They even provide this functionality for the execution of certain tasks, methods, or functions. Javascript does not provide any such sleep method to delay the execution. But we can externally write our code to get such functionality in JavaScript. The behavior of JavaScript is asynchronous. So, it provides promises to handle such asynchronous behavior. Depending on the conditions we can reject and resolve the promise to be sent. Along with this, there are async/await functions that can prove to be helpful to implement sleep kind of functionality in javascript.
How to Implement Sleep Function in JavaScript?
To implement and understand the sleep concept in JavaScript, it is very important to understand how JavaScript code execution happens. So, we will first see the execution model of JavaScript with the help of comparing it with another synchronous language. Ruby is one such language that executes synchronously but when multithreading comes into the picture, ruby can behave sometimes asynchronous.
Consider Ruby Code:
require 'net/http' require 'json'
sampleUrl = 'https://api.github.com/issues' sampleUri = URI(sampleUrl)
sampleResponse = JSON.parse(Net::HTTP.get(sampleUri)) puts sampleResponse['message']
puts "Hey!Let us have a look on message."
Output:
Where “Not Found” is the message string stored in the issues section on the mentioned github url.
Example in JavaScript
Code:
<!DOCTYPE html>
<html>
<body>
<script> fetch('https://api.github.com/issues')
.then(sampleResponse => sampleResponse.json())
.then(sampleJson => console.log(sampleJson.message)); console.log("Hello!");
</script>
</body>
</html>
Output:
As we can see in ruby, firstly the data from the URL is fetched, and then the message property value “Not Found” is displayed and after that the static message saying “Hey! Let us have a look at message.” is displayed while in case of JavaScript, firstly the request for getting the URL data is sent and JavaScript does not wait till the response comes, instead it executes the second statement displaying “Hello” on console and when the response of the sent request arrives, it displays the message value saying “Not Found”. Refer to the URL https://api.github.com/issues to get the data referred for displaying. Here, we can observe the asynchronous behavior of JavaScript as it does not waits for anything while execution and continues its work further.
Syntax of JavaScript Sleep Function:
sleep(delayTime in milliseconds).then(() => {
//code to be executed
})
We can use sleep along with await and async functionalities to get the delay or pause between our executions.
Syntax of using the same.
const myDelayedFunction = async () => { await sleep(delayTime in milliseconds)
//code to be executed
}
myDelayedFunction()
await function helps to wait or pause the execution in the async functions for the promise to be retrieved whether it be resolved or rejected until the execution of the async function. The above syntaxes are just a reference to how we can define and implement sleep functionality by writing such functions in our code. Actual sleep implementation can be achieved by using the timeout events in javascript.
Examples of JavaScript Sleep
Given below are the examples of JavaScript Sleep:
Example #1
Code:
<!DOCTYPE html>
<html>
<body>
<script>
function mySleepFunction(delayTime) {
return new Promise(resolve => setTimeout(resolve, delayTime));
}
async function myDelayedFunction() { document.write('Javascript Sleep Functionality Execution'); for (let counter = 1; counter <11 ; counter++) {
await mySleepFunction(5000);
document.write( counter +" "+"Sample Sleep Execution with the help of timeout event" + " "
+ "</br>");
}
}
myDelayedFunction()
</script>
</body>
</html>
The above code explains how sleep like usage can be implemented in javascript. Here, mySleepFunction is a method that takes the delayTime in milliseconds and returns the promise which is resolved after 5000 milliseconds with the help of a setTimeout timer event in javascript. Instead of setTimeout, setInterval event can also be used in case if you want to execute a certain event repetitively. Here, I have called mySleepFunction repetitively but setTimeout event in it returns promise only once after it is called. After every 5000 milliseconds that are 5 seconds the message “Sample Sleep Execution with the help of timeout event” will be displayed along with the counter value. This will be done 10 times as the loop will iterate for ten times.
Output:
After every five seconds, one message is added in the output.
Example #2
Sleep functionality can be easily achieved by using setTimeOut but it is necessary to consider the asynchronous behavior of setTimeout too.
Code:
<!DOCTYPE html>
<html>
<body>
<script>
console.log("Firstly,Let us Welcome you all for learning javscript");
setTimeout(() => { console.log("This is how javscript makes coding simpler!"); }, 2000); console.log("Here we conclude our session.");
</script>
</body>
</html>
Output:
As can be seen from the above output, the concluding statement is displayed before the statement put in the setTimeout event.
Example #3
We can even use then callback instead of async and await but that makes the code look bit clumsy.
Code:
<!DOCTYPE html>
<html>
<body>
<script>
function sleep(milliseconds) {
return new Promise(resolvePromise => setTimeout(resolvePromise, milliseconds));
}
console.log("Firstly,Let us Welcome you all for learning javscript."); sleep(1000)
.then(() => { console.log("This is how javscript makes coding simpler!"); })
.then(() => { sleep(1000)
.then(() => { console.log("Here we conclude our session."); })
});
</script>
</body>
</html>
Output: