防抖和节流的实现
2019-07-18 本文已影响0人
落花夕拾
/*节流的实现*/
function thottle(fn) {
let timer;
return function(){
if(!timer){
timer = setTimeout(()=>{
fn.apply(this, arguments);
timer= null;
},5000)
}
}
}
function sy(){
console.log("jiuliu")
}
//应用
window.onscroll = throttle(sy)
//结果:每隔5000ms执行一次
//防抖
function debounce(fun){
let timer= null;
return function(){
clearTimeout(timer)
timer = setTimeout(()=>{
fun.apply(this,arguments)
},5000)
}
}
//应用
window.onscroll = debounce(sy)
//结果 总是执行最后一次行为后的结果