Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 accepting 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);
}
like image 418
shmuel613 Avatar asked Sep 01 '10 09:09

shmuel613


3 Answers

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).

like image 79
Nick Craver Avatar answered Oct 17 '22 22:10

Nick Craver


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

like image 22
Strelok Avatar answered Oct 17 '22 23:10

Strelok


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.
like image 27
aularon Avatar answered Oct 17 '22 22:10

aularon