防抖和节流
函数防抖,debounce,基本思路就是把多个信号合并为一个信号,也就是在一定时间内,某方法不再被触发了,就执行该方法。
函数节流,throttle,基本思路就是让用户的方法在某个时间段内只执行一次。
两者间的核心区别就在于持续触发事件时,前者合并事件并在最后时间去触发事件,而后者则是隔间时间触发一次~
debounce 防抖
function debounce(fn,delay){
var timeout;
return function(){
clearTimeout(timeout);
var context = this,
arg = arguments,
timeout = setTimeout(function(){
fn.apply(context,args);
},delay);
}
}
throttle 节流
function throttle(fn,threshhold){
var timeout;
var start = new Date();
var threshhold = threshhold || 160;
return function(){
var context = this,
args = arguments,
curr = new Date()-0;
clearTimeout(timeout);// 总是干掉事件回调
if(curr-start >= threshhold){
fn.apply(context,args); //方法在某段时间内只执行一次
start = curr;
}
else{
//让方法脱离事件后也能执行一次
timeout = setTimeout(function(){
fn.apply(context,args);
},threshhold)
}
}
}
网友评论