防抖:
function debounce(fn, delay) {
var timer = null;
return () => {
clearTimeout(timer)
timer = setTimeout(() => {
fn.call(this)
}, delay)
}
}
const test = debounce(() => {
console.log('防抖');
},2000)
节流:
function throttle(fn, delay) {
//记录上一次函数触发的时间
var lastTime = 0;
return function () {
//记录当前函数触发的时间
var nowTime = Date.now();
if (nowTime - lastTime > delay) {
//修正this指向问题
fn.call(this);
//同步执行结束时间
lastTime = nowTime;
}
}
}
const test1 = throttle (function () {
console.log('事件被触发了' + Date.now());
}, 20000);