Why not just use the setTimeout method of the window object? Bingo, that's right! If you often need to "delay the execution of a certain function" in an application, then based on the DRY principle, you can extend the Function global object and add a delay method such as delay to the function. This will allow Your code is more concise and efficient.
The delay method added to the function object of the expanded site is as follows:
Function.prototype.delay=function(this1,timeout){
this1=this1||null;
timeout=timeout||0;
var _this=this;
var args=[];
//Get parameters, note: the first and second parameters are reserved parameters
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
if(i>1){args.push(arguments[i]);};
};
break;
};
var proxy=function( ){
_this.apply(this1,args);
};
return window.setTimeout(proxy,timeout);
};
firebug in firefox Test under the plug-in console, the 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");