20

I have some jquery and am trying to apply a delay to it but can't seem to get it to work.

The current jquery is as follows...

image.css({"visibility" : "hidden"}).removeClass("image-background");

and I have tried ammending this according to the jquery website (http://api.jquery.com/delay/) to apply the delay...

image.delay(800).css({"visibility" : "hidden"}).removeClass("image-background");

but this doesn't seem to make any difference.

Can anyone see a problem with this? Or how I could fix the problem?

Thanks in advance.

Phil
  • 1,610
  • 4
  • 26
  • 40

2 Answers2

42

The delay() function only applies to actions queued on the element. Most commonly, but not always, these are actions created by the animate() method. In this case, use setTimeout to run some code after a specified interval.

Try this:

setTimeout(function() {
    image.css({"visibility" : "hidden"}).removeClass("image-background");
}, 800);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
35

.delay() is not only for animations.

It's for anything in a queue.

image.delay(800)
     .queue(function( nxt ) {
         $(this).css({"visibility":"hidden"}).removeClass("image-background");
         nxt(); // continue the queue
     });

For the down voter:

HERE'S A DEMO

RightSaidFred
  • 11,209
  • 35
  • 35
  • 8
    Oh, the uninformed down voters strike again. This answer is absolutely correct, and doesn't give wrong information like the others. I guess on StackOverflow that means it should be down voted. – RightSaidFred Dec 06 '11 at 15:18
  • Thank you for not only saying what `delay()` does, but for showing `queue()` as well. – Adarsha Apr 25 '18 at 19:38