Ian Davis
Ian Davis

Reputation: 19423

jQuery .delay does not delay

How can I set the html of an element, wait 2 seconds, then set the html to something else?

Example: $("div").html("clicked").delay(2000).html("2 seconds have passed");

What happens: the div gets "2 seconds have passed" off the bat, instead of saying "clicked" for 2 seconds, then displaying "2 seconds have passed".

Do I need to do something like, .delay(2000, function() { $("div").html("2 seconds have passed"); })?

Live example here: http://jsbin.com/UfaYusU/1/edit

Thanks!

Upvotes: 0

Views: 103

Answers (3)

Ram
Ram

Reputation: 144689

.delay() by default only works with animating functions, you can use .promise() method:

$("div").html("clicked").delay(2000).promise().done(function() {
    $(this).html("2 seconds have passed");
});

Upvotes: 2

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Use setTimeout() if you want to run some code after a delay...

$("button").click(function(e) {
  $("div").html("clicked");
  setTimeout(function() {
    $("div").html("2 seconds have passed");
  }, 2000);
});

Here's an updated version of your jsbin...

Upvotes: 0

GrampaRay
GrampaRay

Reputation: 170

$.delay is used to delay animations in a queue, not halt execution.

Try this:

setTimeout(function() {
      // Do something after 2 seconds
}, 2000);

Upvotes: 3

Related Questions