js手写打卡Day01
js
// 事件触发后等待n秒才执行,期间如果重新触发就重新计时
// 每次触发清除一个定时器,再设置定时器
// 尾执行
const debounce = (fn,delay) => {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this,args);
},delay)
}
}
/* const log = debounce(()=> console.log('hello world'),1000);
log();
log();
log();
*/
// 立即执行
// 在尾执行的基础上加一个首执行
const debounce2 = (fn, delay, immediate) => {
let timer = null;
if (immediate === false) {
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
} else {
return function (...args) {
if (!timer) {
fn.apply(this, args);
}
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
}, delay);
}
}
}
const log = debounce2(()=> console.log('hello world'),1000,false);
log();
log();
log();