// 防抖函数实现 function debounce(fn, delay = 200) { let timer = null; return function () { let context = this; let args = arguments; // 如果此时存在定时器的话,择取消之前的定时器重新计时 if (timer) { clearTimeout(timer); } timer = setTimeout(() => { // 执行函数 fn.apply(context, args); timer = null; }, delay); } }节流函数的实现
// 函数节流的实现 function throttle(fn, delay = 200) { let preTime = null; return function() { let context = this; let args = arguments; let now = Date.now(); if (fn._timer) { clearTimeout(fn._timer); delete fn._timer; } let gapTime = now - preTime; // 如果时间间隔大于或等于规定的间隔时间,那么就执行 if (preTime && gapTime >= delay) { preTime = now; return fn.apply(context, args); } // 否则启动计时器,保证在间隔时间的最后一刻能执行 else { fn._timer = setTimeout(() => { preTime = now; delete fn._timer; fn.apply(context, args); }, delay - gapTime) } } }