Introduction
In this blog, we will learn the Javascript version of sleep() like other programming languages, JavaScript does not include a built-in sleep function. A few methods for replicating the sleep() procedure can be used to implement the JavaScript alternative of sleep. We could use the sleep() function more easily because of JavaScript's features like promises and the async/await function.
Example
Here we will discuss an example of how we can create a sleep function in JavaScript. JavaScript is synchronous and single-threaded and once any process is executed, it can return true immediately. The sleep function will run after the function is entirely executed. We have used async /await and made the sleep function so that it resolves the promise after 1000 milliseconds.
<html>
<head></head>
<body>
<p> alternative of sleep() in JavaScript </p>
<script>
function sleep(milliseconds) {
return new Promise((res) => setTimeout(res, milliseconds));
}
async function name() {
for (let i = 1; i <= 15; i++) {
await sleep(1000);
document.write(i + " " + "Ishika tiwari" + " " + " < /br>");
}
}
name();
</script>
</body>
</html>
Output
Conclusion
This is how we can create a sleep function and use it in JavaScript.
Thanks, I hope this will help you.