Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 739
NovumCoder Avatar asked Sep 09 '10 11:09

NovumCoder


People also ask

How do you write a delay in JavaScript?

The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console. log("Hello"); setTimeout(() => { console.

What is the use of delay () method in jQuery?

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

What is delay function in JavaScript?

What is setTimeout() in JavaScript? setTimeout() is a method that will execute a piece of code after the timer has finished running. Here is the syntax for the setTimeout() method. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); Let's break down the syntax.


1 Answers

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.

like image 171
Andy E Avatar answered Sep 18 '22 15:09

Andy E