.delay() and .setTimeout()

According to jQuery document on .delay(),

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.

Could someone please expand on this? When is it more appropriate to use .delay(), and when is it better to use .setTimeout()?


Solution 1:

I think what you posted explains itself really.

Use .delay() for jQuery effects including animations.

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

Solution 2:

As far as I understand, .delay() is meant specifically for adding a delay between methods in a given jQuery queue. For example, if you wanted to fade an image into view during the span of 1 second, have it visible for 5 seconds, and then spend another second to fade it out of view again, you could do the following:

$('#image').fadeIn(1000).delay(5000).fadeOut(1000);

In this instance, .delay() is more intuitive to use since it is specifically meant for delaying events in a given jQuery queue. setImeout(), on the other hand, is a native JavaScript method that isn't intended explicitly for a queue line. If you wanted an alert box to pop up 1 second after clicking on a button, you could do the following:

function delayAlert() {
    var x = setTimeout("alert('5 seconds later!')", 5000);
}

<input type="submit" value="Delay!" onclick="delayAlert();" />

Solution 3:

You can use delay with animations, for example:

$('.message').delay(5000).fadeOut();

You can also use timeOut to delay the start of animations, for example:

window.setTimeout(function(){
  $('.message').fadeOut();
}, 5000);

As you see, it's easier to use delay than setTimeout with animations.

You can delay pretty much anything with setTimeout, but you can only delay animations with delay. Methods that aren't animations are not affected by delay, so this would not wait a while before hiding the element, it would hide it immediately:

$('.message').delay(5000).hide();