tags:

views:

46

answers:

2

Hi all,

i have strange problem with the delay function here using the html function with it.

I set a 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 doesnt 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 doesnt this work. Its a pretty simple, wait 3 seconds then run the html function.

Could anybody advise? Thanks.

PS: For your info, i use jQuery 1.4.2

+3  A: 

.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.

Nick Craver
+3  A: 

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.

Andy E
To be more accurate, `.delay()` applies to *any* queue, it just *defaults* to the animation queue :)
Nick Craver
@Nick: thanks for the correction, updated :-)
Andy E
Thanks this one is working now.One more question: does this work on all browsers? im not sure if window.setTimeout will work in all IE and FF versions.
NovumCoder
@NovumCoder - Yes this works across the board :)
Nick Craver
@NovumCoder: *window.setTimeout()* goes way back to JavaScript 1.0 and was adopted by IE in IE 5 (I think). I've yet to discover a browser that doesn't implement it, and now it's part of the proposed [HTML5 specification](http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers)
Andy E