实现
function handle(data) {
console.log('防抖:',data);
}
var canRun = true;
function throttle(data,delay) {
// 通过闭包保存一个标记
return function () {
// 在函数开头判断标记是否为true,不为true则return
if (!canRun) {
return;
}
// 立即设置为false
canRun = false;
// 将外部传入的函数的执行放在setTimeout中
setTimeout(function() {
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
// 当定时器没有执行的时候标记永远是false,在开头被return掉
// fn.apply(this, arguments);
handle(data)
canRun = true;
}, delay);
};
}
window.addEventListener('click', throttle(data,500));