I want something like this in javascript.
for (i = 0; i < 10; i++) {
alert(i);
// now sleep 1 sec
sleep(1000);
}
is there a built in Javascript or Jquery for this?
Thank you!
Unlike Java or Python, Javascript does not have a built-in sleep function. So, how might you be able to implement a method with the same functionality as the sleep function? A simple way to create a delay in Javascript is to use the setTimeout method.
The JavaScript version of sleep() is “await”. The await feature pauses the current aync function.
The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.
JavaScript may not have a sleep() or wait() function, but it is easy enough to create one using the built-in setTimeout() function — as long as you are careful with how you use it.
There's no such thing, directly. You would have to tell javascript to wake 'something' up after some time using setTimeout
.
This 'something' would be the code that you plan to execute after the sleep, of course.
From an example I found on the internet:
function dothingswithsleep( part ) {
if( part == 0 ) {
alert( "before sleep" );
setTimeout( function() { dothingswithsleep( 1 ); }, 1000 );
} else if( part == 1 ) {
alert( "after sleep" );
}
}
But that's fragile design. You better rethink your business logic to really do something after a second: call a different function instead of using these contrived helper variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With