防抖
export const debounce = (fn, delay) => {
let timer = null;
let that = this;
return (...args) => {
timer && clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(that, args);
}, delay);
}
}
节流
// 定时器版
export const throttle = (fn, delay) => {
let timer = null;
let that = this;
return (args) => {
if (timer) return;
timer = setTimeout(() => {
fn().apply(that, args);
timer = null;
}, delay);
}
}
// 时间戳版
function throttle(fn, delay) {
var previous = 0;
// 使用闭包返回一个函数并且用到闭包函数外面的变量previous
return function() {
var _this = this;
var args = arguments;
var now = new Date();
if(now - previous > delay) {
fn.apply(_this, args);
previous = now;
}
}
}