在浏览器 DOM 事件里面,有一些事件会随着用户的操作不间断触发。比如:重新调整浏览器窗口大小(resize),浏览器页面滚动(scroll),鼠标移动(mousemove)。
也就是说用户在触发这些浏览器操作的时候,如果脚本里面绑定了对应的事件处理方法,这个方法就不停的触发。而当事件处理比较复杂的时候浏览器不断执行计算,从而导致浏览器性能降低甚至卡死,影响用户体验。
下面我们就针对这一情况做函数的节流处理(以weindow.scroll为例)。
1、简单实现(未用闭包)
var timer = null;
window.onscroll = function () {
clearTimeout(timer);
timer = setTimeout(function() {
console.log(new Date().getTime());
}, 200);
};
2、利用闭包进行改进
var throttle = function (fn,delay) {
var timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(function() {
fn();
}, delay);
}
};
function testFn (){
console.log(new Date().getTime());
}
window.onscroll = throttle(testFn, 200);
3、利用函数的私有变量保存tId
function throttle (method,context,delay) {//context用来保存this指向
clearTimeout(method.tId);
method.tId = setTimeout(function () {
method.call(context);
},delay)
}
function testFn(){
console.log(new Date().getTime());
}
window.onscroll = throttle(testFn,null,100);
上面这些方法已经可以起到节流效果了,但是会有一个问题。就是当用户不断的出发scroll事件的时候,我们所需要执行的函数一次也不会执行,所以我们就需要设置一个最小触发时间,接下来我们对throttle函数再次进行改进。
//fn执行函数 delay停止触发事件多长时间后执行函数 minTime不断触发时强制执行时间
var throttle = function (fn,delay,minTime) {
if (typeof fn !== 'function') return new Function()
var timer = null;
var starTime = null;
return function () {
var now = +new Date();
!starTime && (starTime = now);
if( minTime && now - starTime > minTime ) {
fn();
starTime = now;//将开始时间重置
}else{
clearTimeout(timer);
timer = setTimeout(function() {
fn();
starTime = null;
}, delay);
}
}
};
function testFn(){
console.log(new Date().getTime());
}
window.onscroll = throttle(testFn,200,300);
这样只需要传入minTime最小触发时间就可以了。