Isn't the setTimeout method of the window object used? Bingo, that's right! If you often need to "execute a certain Function with latency" in an application, you can extend the global object of the Function Based on the DRY principle and add a delay method such as delay for the Function, this will make your code more concise and effective.
The method for adding delay to the expansion Function object is as follows:
Copy codeThe Code is as follows:
Function. prototype. delay = function (this1, timeout ){
This1 = this1 | null;
Timeout = timeout | 0;
Var _ this = this;
Var args = [];
// Obtain parameters. Note: 1st and 2nd parameters are reserved.
Switch (arguments. length ){
Case 1:
Timeout = parseInt (arguments [0]);
Timeout = isNaN (timeout )? 0: timeout;
Timeout = timeout <0? 0: timeout;
Break;
Default:
For (var I = 0; I <arguments. length; I ++ ){
If (I> 1) {args. push (arguments [I]) ;};
};
Break;
};
Var proxy = function (){
_ This. apply (this1, args );
};
Return window. setTimeout (proxy, timeout );
};
Test the code in the firebug plug-in console of firefox, for example:
Copy codeThe Code is as follows:
Var xx = function (n ){
This. name = n;
};
Xx. prototype. hi = function (a, B ){
Console. log (this. name + "-" + a + "-" + B );
};
Var xx1 = new xx ("levin ");
Var t = xx1.hi. delay (xx1, 1000, "cocoa", "yoyo ");
Xx1.hi ("guluglu", "jigujigu ");