(作者笔记自用)
function throttle(fn, range){
range = range || 1000;
let timer;
return () => {
if(!timer){
timer = setTimeout(() => {
fn();
timer = null;
}, range);
}
}
}
function print() {
console.log('print');
}
window.addEventListener('mousemove', throttle(print, 3000), false);
用处:在设置的时间段内只触发第一次的函数调用请求,无视掉其他的函数调用请求,如以上代码,如果你在网页中一直移动鼠标,fn函数,即print函数每三秒调用一次。