Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 425
Mahmoud Saleh Avatar asked Dec 14 '10 09:12

Mahmoud Saleh


People also ask

What is delay in jQuery?

jQuery delay() Method The delay() method sets a timer to delay the execution of the next item in the queue.

What does sleep do in JavaScript?

With the help of Sleep() we can make a function to pause execution for a fixed amount of time. In programming languages such as C and Php we would call sleep(sec).

Is there a sleep in JavaScript?

Unlike Java or Python, Javascript does not have a built-in sleep function.

Why is there no sleep in JavaScript?

Many programming languages have a sleep function that will delay a program's execution for a given number of seconds. However, this functionality is absent from JavaScript due to its asynchronous nature.


3 Answers

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);
like image 135
Nick Craver Avatar answered Sep 30 '22 01:09

Nick Craver


Here ya go!

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

function moomoo() {
  $("#div2").show();
}
like image 39
Barrie Reader Avatar answered Sep 30 '22 02:09

Barrie Reader


The following should do what you want:

$("#div1").hide();
$("#div2").delay(1000).show(0);
like image 25
Marcus Stade Avatar answered Sep 30 '22 03:09

Marcus Stade