After arriving at Sohu, I was busy. I haven't written essays in the garden for a long time ~~
This article mainly introduces "how to execute a function at a delay in JS ?"
Isn't the setTimeout method of the window object used? Bingo, that's right! If youThe application often needs to "delay the execution of a certain function"Then, based on the dry principle, you can expand the global objects of the function, and add a delay method such as delay for the function, which will make your code more concise and effective.
The method for adding delay to the expansion function object is as follows:
Code
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:
Code
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");