一.函数节流和函数去斗是解决什么问题的:
大家都知道,人的眼睛能感知的最快反应速度是在0.1秒到0.4秒之间,所以0.1秒内的变化从视觉上来说是无意义的。而且如果涉及dom操作,或者网络操作会严重浪费资源,可能导致浏览器崩溃,或者服务器崩溃。例如一下场景:
(1)浏览器滚动事件scroll
(2) 鼠标的点击事件 mouseup, mousedown,mousemove
(3) 键盘的keyup, keydown, input事件
(4)window的resize事件
以上四个场景中,事件都是连续触发的,如果也连续执行相应的回调函数,不但浪费资源,而且没有意义,还有可能导致浏览器或者服务器崩溃。 函数节流和函数去斗就是为了解决类似这样问题的。
二.思想及简单实现:
函数节流:
设定一个时间周期,周期性的执行一个函数;
var _throttle = function (wait, fn) {
var pre = 0, result;
return function(){
var now = (new Date()).getTime();
if(now-pre > wait) {
result = fn.apply();
pre = now;
return result;
}
}
};
// 用setInterval模拟每10毫秒执行一次,但真正的执行时间是10秒
var throttle = _throttle(10000, function(){
console.log("*******************")
});
setInterval(throttle, 10);
函数去斗:
设定一个延迟时间,延迟时间到了再去执行函数,如果在延迟时间内重复调用则重新计算延迟时间
var _debounce = function(wait, fn){
var timer = null;
return function(){
if(timer){
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function(){
var result = fn.apply();
clearTimeout(timer);
timer = null;
return result;
}, wait)
}
};
// 用setTimeout模拟1秒中调用一次,每次调用都会重置时间。函数真正执行时间是在 8秒后
var debounce = _debounce(3000, function(){
console.log('*******************')
});
setTimeout(debounce,1000);
setTimeout(debounce,2000);
setTimeout(debounce,3000);
setTimeout(debounce,4000);
setTimeout(debounce,5000);