定时器timer的进一步引用


定时器:times的单位为毫秒。
var timer = setTimeout(fn,times); //在time时间以后执行函数fn.
如果times = 0,则表示,希望fn“尽可能快”的得到执行。


var timer = setInterval(fn,times);
//时间间隔为time,重复执行函数fn.如果fn的执行时间长于时间间隔times,那么接下来的那次将紧接着执行。
因此,如果希望每一次fn执行完了以后,经历时间间隔times都可以再一次执行(有可能被其它情况打断),
可以使用fn函数结尾调用setTimeout函数来实现。
setTimeout(function(){
//processing
setTimeout(arguments.callee, interval);
}, interval);


Timer的一个应用:
var processor = {
timeoutId: null,
//method that actually performs the processing
performProcessing: function(){
//actual processing code
},
//method that is called to initiate processing
process: function(){
//不过有没有执行,把它取消。
clearTimeout(this.timeoutId);
var that = this;
this.timeoutId = setTimeout(function(){
that.performProcessing();
}, 100);
}
};
//try to start processing
processor.process();
在这个模式中,可以保证,即使在100毫秒以内process()被调用了多次,那么performProcessing最终也只会被执行一次。
可以用以下一个精简的函数实现上面的功能:

function throttle(method, context) {
clearTimeout(method.tId);
method.tId= setTimeout(function(){
method.call(context);
}, 100);
}
在IE中,window的resize事件会调用函数多次。我们可以通过throttle函数来消除这种问题。
function resizeDiv(){
var div = document.getElementById("myDiv");
div.style.height = div.offsetWidth + "px";
}
window.onresize = function(){
throttle(resizeDiv);
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值