// 进阶版:首次触发立即执行 immediate标识是否第一次执行
//debounce
const debounce1 = (fn, delay, immediate = true) => {
let timer = null;
return (...args) => {
// new code start
if (immediate && !timer) {
//执行fn
fn.apply(this, args);
}
//new code end
// 更新计时器
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
//throttle
//版本一 采用时间戳
const throttle = (fn,delay) => {
// 记录上一次执行的时间,闭包特性
let previous = 0;
return (...args) => {
//记录当前时间
let now = +new Date();
if(now - previous > delay) {
//更新时间
previous = now;
//执行函数
fn.apply(this,args);
}
}
}
console