function throttle(fn, interval) {
let _lastTime = null;
return function() {
let _nowTime = new Date().getTime();
if(_nowTime - _lastTime > interval || !_lastTime) {
fn();
_lastTime = _nowTime;
}
}
}
let fn = () => {
console.log('boom');
}
setTinterval(throttle(fn,1000),10) // 每1秒打印一个boom
function debounce(fn, wait) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if(timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
fn.apply(context, args);
}, wait);
}
}
let fn = () => {
console.log('boom');
}
setTnterval(debounce(fn, 500), 1000) // 第一次在1500ms后触发,之后每1000ms触发一次
setInterval(debounce(fn, 2000), 1000) // 不会触发