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 figur开发者_如何学JAVAe out how to wait 3 seconds but not interrupt the main control flow?
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.
It is basically using timeouts with your time that you put into the delay function.
See the source code here: http://james.padolsey.com/jquery/#v=1.6.2&fn=delay
The code for queue and dequeue are also useful:
http://james.padolsey.com/jquery/#v=1.6.2&fn=queue
http://james.padolsey.com/jquery/#v=1.6.2&fn=jQuery.dequeue
精彩评论