Using delay with HTML or text setting doesn't work

I have strange problem with the delay function here using the HTML function with it.

I set an HTML text by using $( '#element').html( 'Hello World');

After setting the text I want to get this text disappear in 3 seconds.

So next line I wrote:

$('#element').delay( 3000).html( '&nbsp');

This one doesn't work, it sets the HTML to &nbsp without waiting the 3 seconds, it looks like jQuery is skipping the delay function. Using this with fadeOut for example works fine. I guess this has something to do with this queue thing in delay.

But why doesn't this work. Its a pretty simple, wait 3 seconds then run the HTML function.

Answers:

Answer

delay() defaults to the animation queue, for effects like fadeOut(), etc. You should use setTimeout() instead:

window.setTimeout(function () {
    $("#element").html(' ');
}, 3000);

From http://api.jquery.com/delay/:

jQuery.delay() is best for delaying between queued jQuery effects and such, and is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

Answer

.html() isn't a queued function. If you want it to happen in order in the animation queue, you'll have to .queue() it yourself, like this:

$('#element').delay(3000).queue(function(n) { 
  $(this).html('&nbsp'); n();
});

If you're not chaining animations or anything like this, use setTimeout() or setInterval() (whichever is appropriate to the situation) directly, .delay() is just a wrapper for setTimeout() and there's no reason to use extra code/complexity when there's no need.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.