igetstuckalot
igetstuckalot

Reputation: 237

jQuery delay not working properly

I cant seem to get my text to update, with a delay of 0.8seconds.

function beginningText() {
 $('#bubbleText').text('H').delay(800);
$('#bubbleText').text('He');
}

Upvotes: 1

Views: 1648

Answers (2)

Vatsal
Vatsal

Reputation: 2128

You probably want set timeout here and not delay. There is s

Created a fiddle for you https://jsfiddle.net/vatsalpande/5d09nbLo/

Sample Code

$(document).ready(function(){

function beginningText() {

    $('#bubbleText').text('H');
    setTimeout(function(){ $('#bubbleText').text('HE') }, 3000);

   }
 beginningText();

});

<div id = "bubbleText"></div>

As per jQuery Documentation

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

So the keypoints to take away are

  1. Use .delay() for jQuery effects including animations.

  2. setTimeout() is best used for everything else. For example when you need to trigger an event at a certain elapsed time.

Hope this be of some help.

Happy Learning

Upvotes: 1

David
David

Reputation: 218847

.delay() blocks code which chains from it on the same statement, but not code which comes on statements after it.

Technically the structure you want is this:

$('#bubbleText').text('H').delay(800).text('He');

However, this won't work. For a very non-obvious reason (that I just had to look up). .delay() operates on items that are "queued" in jQuery, such as animations and other things which, well, take time. Setting text, or any other such "instant" operation, isn't "queued" and just happens immediately.

You can manually add operations to the queue with the .queue() function:

$('#bubbleText').text('H').delay(800).queue(function(){
    $('#bubbleText').text('He');
});

Upvotes: 1

Related Questions