工具函数系列-节流throttle
节流的原理是:固定时间间隔执行函数
应用场景:resize
、scroll
function throttle(func, wait) {
var timeout, context, args;
var previous = 0;
var later = function() {
previous = +new Date();
timeout = null;
func.apply(context, args)
};
var throttled = function() {
var now = +new Date();
//下次触发 func 剩余的时间
var remaining = wait - (now - previous);
context = this;
args = arguments;
// 如果没有剩余的时间了或者你改了系统时间
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
};
return throttled;
}
function throttle2(func, wait) {
var timeout = null;
var previous = 0;
return function() {
var args = arguments;
var context = this;
var now = +new Date();
var remainning = wait - (now - previous); // 等待时间减去两次触发事件的时间差
timeout && clearTimeout(timeout)
if (remainning <= 0) { // 两次触发时间差大于等待时间,立马执行
func.apply(context, args)
previous = now // 更新时间
} else { // 小于等待时间,等待一段时间后执行
timeout = setTimeout(function () {
func.apply(context, args)
provious = +new Date()
}, remainning) // 修改设置timeout时间
}
}
}
我们可以看到:鼠标移入,事件立刻执行,晃了 3s,事件再一次执行,当数字变成 3 的时候,也就是 6s 后,我们立刻移出鼠标,停止触发事件,9s 的时候,依然会再执行一次事件。