以前不知道这些名词,然后看了这篇文章知道了。
【前端性能】高性能滚动 scroll 及页面渲染优化 - ChokCoco - 博客园
防抖(Debouncing)
像防抖还是很容易想到的,大概意思就是延时处理,然后如果在这段延时内又触发了事件,则重新开始延时。
看代码最直观啦。
// 简单示例
window.addEventListener('resize',function(e){
var t;
return function(){
if(t) clearTimeout(t);
t = setTimeout(function(){
// do something...
},500);
}
}());
节流(Throttling)
有的情况下,防抖是不能满足需求的。
抄来代码
// 简单的节流函数
function throttle(func, wait, mustRun) {
var timeout,
startTime = new Date();
return function() {
var context = this,
args = arguments,
curTime = new Date();
clearTimeout(timeout);
// 如果达到了规定的触发时间间隔,触发 handler
if(curTime - startTime >= mustRun){
func.apply(context,args);
startTime = curTime;
// 没达到触发间隔,重新设定定时器
}else{
timeout = setTimeout(func, wait);
}
};
};
// 实际想绑定在 scroll 事件上的 handler
function realFunc(){
console.log("Success");
}
// 采用了节流函数
window.addEventListener('scroll',throttle(realFunc,500,1000));