Introduction
Sometimes, we may wish to sleep()
for a specific period in a JavaScript program. In this post, we'll learn how to do it.
How to hold running JavaScript program for a specific time (alternative to sleep()
function in other programming languages)
To sleep()
your application in JavaScript you can use Promise
, setTimeout()
and await
:
const sleep = ms => new Promise(r => setTimeout(r, ms));
This sleep()
function will hold the running program for a given period in milliseconds.
await sleep(<duration>); // duration in milliseconds
If you want to run code after a specific time you can use the following code:
sleep(500).then(() => {
// Do something after sleep!
});
In case you don't want to use the setTimeout()
function you can use the following:
function sleep(duration) {
var now = new Date().getTime();
while(new Date().getTime() < now + duration) {
/* Do nothing */
}
}
sleep(2000);
console.log("Hello, FrontBackend after sleep!");
Conclusion
In this post, we presented the best way to sleep() in JavaScript.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}