Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent Javascript or Jquery sleep function?

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!

like image 478
Flueras Bogdan Avatar asked Aug 14 '09 10:08

Flueras Bogdan


People also ask

Is there any sleep function in JavaScript?

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.

What is the JavaScript version of sleep?

The JavaScript version of sleep() is “await”. The await feature pauses the current aync function.

What is the alternative for setTimeout in JavaScript?

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.

Does JavaScript have a wait function?

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.


1 Answers

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.

like image 90
xtofl Avatar answered Oct 21 '22 14:10

xtofl