您的位置:首页 > 其它

函数防抖和函数节流

2018-08-28 17:49 483 查看

函数防抖(debounce)

当调用动作过n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间

如果有人进电梯(触发事件),那电梯将在10秒钟后出发(执行事件监听器),这时如果又有人进电梯了(在10秒内再次触发该事件),我们又得等10秒再出发(重新计时)

函数节流(throttle) 

预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新周期 

保证如果电梯第一个人进来后,10秒后准时运送一次,这个时间从第一个人上电梯开始计时,不等待,如果没有人,则不运行

 函数防抖(debounce)

[code]function _debounce(fn,wait){
var timer = null;
return function(){
clearTimeout(timer)  // 清除未执行的代码,重置回初始化状态
timer = setTimeout(()=>{
fn()
},wait)
}
}

function fn(){
console.log(1)
}
window.onscroll = _debounce(fn,500)

优化

[code]       function _debounce(fn,wait,time){
var timer = null;
var pre = null;
return function (){
var now = +new Date();
if(!pre) pre = now
if(now - pre > time){
//当上一次执行的时间与当前的时间差大于设置的执行间隔时长的话,就主动执行一次
clearTimeout(timer);
fn();
pre = now;
}else{
clearTimeout(timer);
timer = setTimeout(function(){
fn();
},wait)
}
}
}
function fn(){
console.log(1)
}

window.onscroll = _debounce(fn,500,2000)

函数节流(throttle)

[code]      function _throttle(fn, time) {
let timer, firstTime = true;
return function (){
if(firstTime) {
fn();
firstTime = false
}
if(timer){return false}
timer = setTimeout(function(){
clearTimeout(timer)
fn();
timer = null
},500)
}
}
function fn(){
console.log(1)
}
window.onscroll = _throttle(fn,500)

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: