Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery's .delay method work under-the-hood?

I just saw this and think it's cool.

console.log("Starting...");
$("#my_element")
  .fadeIn()
  .delay(3000)
  .fadeOut();
console.log("Finishing...");

How does the .delay method work under-the-hood? I mean, how does it figure out how to wait 3 seconds but not interrupt the main control flow?

like image 713
Geoff Avatar asked Jul 07 '11 21:07

Geoff


People also ask

What is the use of delay method?

delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of . show() or .

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.

How to delay animation in jQuery?

To delay execution of animation, use . delay() method which allows to delay the execution of functions that follow it in the queue. It accepts duration as parameter. Durations are given in milliseconds; higher values indicate slower animations, not faster ones.


1 Answers

jQuery has an internal "queue" object, that is just an array:

[ nextAction,
  action,
  action,
  lastAction ]

When you use delay, it pushes:

function delay( ms ){
   setTimeout( dequeue, ms )
}

Meaning that once it gets to the delay, there's a timeout and then the next action is fired. Actions that happen immediately, like .css, however, do:

function css(){
    // do stuff
    dequeue();
}

no delay.

like image 185
Nobody Avatar answered Sep 21 '22 13:09

Nobody