您的位置:首页 > 其它

防抖与节流

2019-05-12 21:29 267 查看
防抖(多少毫秒之内调用一次,减少代码调用次数,提高性能)
  • 常用于onmousemove,onresize,oninput,onscroll
function debuce(fn,delay){
let timeId=null;
return function(){
let self=this;
let args=arguments;
timeId&&clearTimeout(timeId);
timeId=setTimeout(function(){
fn.apply(self,args);
},delay||1000)
}
}

function test(event){
console.log(this,event)
}
document.getElementById('int').oninput=debuce(test,2000);
节流(多少毫秒之内调用多次,减少代码调用次数,提高性能)
function throttle(fn,delay){
let timeId=null;
let flag=true;
return function(){
if(!flag){
return
}
let self=this;
let args=arguments;
flag=false;
timeId&&clearTimeout(timeId);
timeId=setTimeout(function(){
flag=true;
fn.apply(self,args);
},delay||500)
}
}

function test(event){
console.log(this,event)
}
document.getElementById('int').oninput=throttle(test,1000);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: