Programming languages like PHP and C include a sleep(sec) function that temporarily halts execution for a specified duration. In Java, the equivalent is thread.sleep, while Python uses time.sleep. In the GO programming language, the function is represented as time.sleep(2*time.second).
In contrast to many other programming languages, JavaScript lacks a built-in sleep function. However, there are various methods available to replicate the behavior of a sleep function in JavaScript. The introduction of features like promises and the async/await syntax has significantly simplified the implementation of sleep-like functionality within JavaScript.
The await keyword is employed to pause execution until a promise is resolved and can solely be utilized within an async function. JavaScript operates in an asynchronous fashion, which introduces the use of promises to manage this non-blocking behavior. Due to this asynchronous nature, the execution proceeds without waiting for any tasks to complete. The async/await syntax allows us to structure our code to appear synchronous, enhancing readability and maintainability.
How to use sleep function in JavaScript?
Prior to utilizing the sleep function in JavaScript, it is crucial to comprehend how JavaScript code is executed.
Syntax of sleep in JavaScript
sleep(delayTime in milliseconds).then(() => {
// code to be executed
})
The sleep function can be utilized in conjunction with async/await to introduce a delay in the execution flow. The syntax for implementing this is outlined below:
Syntax
const func = async () => { await sleep(delayTime in milliseconds)
//code to be executed
}
fun()
The syntactical structures outlined above illustrate how to incorporate sleep functionality in JavaScript. Next, we will explore examples demonstrating the usage of the sleep function within JavaScript.
Example1
In this illustration, we will demonstrate the use of the sleep function alongside async/await functionalities. A function named fun is established containing several statements. At the outset, the message "Hello World" is presented on the display when the function is invoked. Subsequently, the sleep function causes the fun to suspend for a duration of 2 seconds. Once this time frame elapses, the message "Welcome to the logic-practice.com" is showcased on the screen, and this text will continue to appear repeatedly until the loop concludes. This message will be repeated a total of 10 times on the screen, with a 2-second pause during each iteration of the loop.
<html>
<head>
</head>
<body>
<h1> Example of using sleep() in JavaScript </h1>
<script>
function sleep(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
async function fun() {
document.write('Hello World');
for (let i = 1; i <=10 ; i++) {
await sleep(2000);
document.write( i + " " + "Welcome to the logic-practice.com" + " " + "</br>");
}
}
fun();
</script>
</body>
</html>
Output
Upon running the code provided above, the resulting output will be -
After two seconds, the output will change -
The loop is designed to execute 10 times, with a delay of 2 seconds occurring at the end of each iteration.
Example2
In this instance, we are generating a promise utilizing the setTimeout function. This function is designed to run code following a designated interval. Additionally, we are employing the then method, which invokes the necessary function once the promise has been fulfilled.
At first, a series of statements will appear on the display. Following a pause of 2 seconds, the text "End" will then be shown on the screen.
This method is favored for introducing a delay in a function. Due to the utilization of promises, it is compatible with ES6.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Example of using the sleep() in JavaScript</h1>
<p>
There is a sleep of 2000 milliseconds
</p>
<script>
let sleep = ms => {
return new Promise(resolve => setTimeout(resolve, ms));
};
document.write("Begin" + "<br>");
document.write("Welcome to the logic-practice.com" + "<br>");
sleep(2000).then(() => {
document.write("End");
});
</script>
</body>
</html>
Output
Upon running the code provided above, the resulting output will be -
Following a pause of 2 seconds, the resulting output will be -