到了搜狐后比较忙,很久没在园子里写随笔了~~
这篇文章主要介绍“在js里面怎么延时执行一个函数?”
不就利用window对象的setTimeout方法吗?Bingo,一点没错!如果你在一个应用里面常常要“延时执行某某函数”,那末基于DRY的原则,可以针对Function全局对象进行扩展,为函数增加一个延时方法如delay,这样会让你的代码更简洁有效。
扩站Function对象增加delay方法如下:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
Function.prototype.delay
=
function
(this1,timeout){
this1 = this1 || null ;
timeout = timeout || 0 ;
var _this = this ;
var args = [];
// 获取参数,注:第1、第2个参数是保留参数
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);
};
this1 = this1 || null ;
timeout = timeout || 0 ;
var _this = this ;
var args = [];
// 获取参数,注:第1、第2个参数是保留参数
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);
};
在firefox的firebug插件的控制台下面测试下,代码如:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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 " );
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 " );