Updated March 28, 2023
Introduction to JavaScript sleep Function
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. To understand the concept of JavaScript sleep Function, we will discuss the execution model of JavaScript in comparison with another synchronous language. Ruby is one language that executes synchronously, but when multithreading comes into the picture, ruby can sometimes behave asynchronously. Consider following ruby code,
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. Consider the same example in javascript,
Code:
<!DOCTYPE html>
<html>
<head>
<h1>Demonstration for asynchronous behavior of javascript</h1>
</head>
<body>
<script>
fetch('https://api.github.com/issues')
.then(sampleResponse => sampleResponse.json())
.then(sampleJson => document.write(sampleJson.message));
document.write("Hello!This is EDUCBA learning platform.");
</script>
</body>
</html>
Output:
And then immediately it gives the output as follows:
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 on 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:
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. Here is the 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 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. This can be achieved in the following manner –
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 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.
Sleep functionality can be easily achieved by using setTimeOut but it is necessary to consider the asynchronous behavior of setTimeout too. Let us understand this with the help of an example.
Code:
<!DOCTYPE html>
<html>
<body>
<script>
document.write("Firstly,Let us Welcome you all for learning javscript</br></br>");
setTimeout(() => { document.write("This is how javascript makes coding simpler!"); }, 2000);
document.write("Here we conclude our session.");
</script>
</body>
</html>
Output:
As seen from the above output, the concluding statement is displayed before the statement is put in the setTimeout event. For such reasons, following the first example’s practice of implementing sleep functionality in javascript is best.
We can even use then callback instead of async and await but that makes the code look bit clumsy. Still, you should know how it is implemented. Here is an example demonstrating the same.
Code:
<!DOCTYPE html>
<html>
<head>
<h1>EDUCBA Demonstration of in Javascript</h1>
</head>sleep functionality
<body>
<script>
function sleep(milliseconds) {
return new Promise(resolvePromise => setTimeout(resolvePromise, milliseconds));
}
document.write("Firstly,Let us Welcome you all at EDUCBA for learning Javascript.");
sleep(1000)
.then(() => { document.write("This is how javscript makes coding simpler!</br></br>"); })
.then(() => {
sleep(1000)
.then(() => { document.write("Here we conclude our session."); })
});
</script>
</body>
</html>
Output:
This works fine. Along with this you also need to consider the browsers and the versions that support the async and await functions while implementing sleep functionality in javascript. Below is the list of browsers and their minimum versions that support this.
Recommended Articles
This is a guide to JavaScript sleep Function. Here we have discussed the Introduction to JavaScript sleep Function, its Examples, and its Code Implementation. You can also go through our other suggested articles to learn more –