Is there a jQuery equivalent to prototype's defer?
Is there a jQuery equivalent to prototype's defer?
I'm looking for something that will delay the execution of a script until all of the scripts in the page are finished executing.
Thanks!
PART II: Is there any way to see if there are other setTimeouts in the queue and delay execution until after they fire? I see in the comments that sometimes setTimeout of 0 or 1 doesn't matter because it's unpredictable as to which will fire first.
Thanks again!
Update to answer
I found a bug in the code that I was using from the answer accepted below. The slice call needs to work on 0, not 1 since in the Prototype core code, it's accep开发者_JAVA技巧ting an extra parameter for the amount of time to wait (0.01). The final method then becomes:
Function.prototype.deferFunc = function() {
var __method = this, args = Array.prototype.slice.call(arguments, 0);
return window.setTimeout(function() {
return __method.apply(__method, args);
}, 0.01);
}
You can use the basic version available in vanilla JavaScript for most purposes, setTimeout()
:
setTimeout(function() {
//do something
}, 0);
A similar queuing mechanism jQuery uses for animations are the callbacks and the .delay()
function (which uses setTimeout()
underneath).
All defer
does is execute the function inside window.setTimeout
with timeout of 0.
You can implement it like this I am sure:
Function.prototype.defer = function() {
var __method = this, args = Array.prototype.slice.call(arguments, 1);
return window.setTimeout(function() {
return __method.apply(__method, args);
}, 0);
}
Demo
you can easily implement it:
Function.prototype.defer=function() {
setTimeout(this, 0);
}
and here's a test:
var testFunc=function() {
alert('first');
}
testFunc.defer();
alert('second');//first the browser will run this line, then will execute the above defered one.
精彩评论