Mahmoud Saleh
Mahmoud Saleh

Reputation: 33605

Sleep in JQuery?

greetings all i want to make JQuery sleep/wait for a second between two functions

$('#div1').hide();
//sleep or wait or for a sec 
$("#div2").show();

how to do so ?

Upvotes: 19

Views: 86686

Answers (5)

Marcus Stade
Marcus Stade

Reputation: 4984

The following should do what you want:

$("#div1").hide();
$("#div2").delay(1000).show(0);

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630429

For your specific function .show() isn't queued, but there's an easy trick to make it queued so you can use .delay(), like this:

$('#div1').hide();
$("#div2").delay(1000).show(0);

By giving it a 0 duration argument, it's now an instant, but queued animation. Underneath this uses setTimeout(), so it's basically the same behavior as:

$('#div1').hide();
setTimeout(function() { $("#div2").show(); }, 1000);

Upvotes: 41

Guffa
Guffa

Reputation: 700362

You can't just pause the execution of the code between the calls. That would mean that the browser would not display the change caused by the hide call, as no updates are done while the code is running. The code would just appear to do nothing.

Use the setTimeout method to schedule code to be executed at a later time:

$('#div1').hide();
window.setTimeout(function(){
  $("#div2").show();
}, 1000);

This will set the element as hidden and schedule the code to show it to start later. The code will continue after the setTimeout call so that the function can exit and the browser gets back the control so that it can actually hide the element.

Upvotes: 2

Shadow Wizard
Shadow Wizard

Reputation: 66388

No real sleep, but this will achieve the same goal:

$('#div1').hide();
//sleep or wait or for a sec 
window.setTimeout(function() { $("#div2").show(); }, 1000);

Edit: well, I now stand corrected about "real" sleep, however using the setTimeout is still valid "pure JS" solution - your choice. :)

Upvotes: 0

Barrie Reader
Barrie Reader

Reputation: 10713

Here ya go!

$('#div1').hide();
//sleep or wait or for a sec 
setTimeout('moomoo()', 1000);

function moomoo() {
  $("#div2").show();
}

Upvotes: 6

Related Questions