函数防抖、函数节流 发表于 2023-03-30 | 分类于 Function 函数防抖 触发事件在n秒后才执行函数,如果在n秒内又触发了事件,则会重新计算函数执行 1234567891011121314151617181920212223242526272829303132333435363738394041/** * * @param {Function} fn 回调 * @param {Number} delay 延迟时间 * @param {Boolean} immediate 是否首次延迟执行、n秒内频繁触发事件,计时器会频繁重新开始计时 */export function debounce(fn, delay, immediate) { var timer = null var debounced = function () { var _self = this, args = arguments; if (timer) { clearTimeout(timer) } if (immediate) { var exec = !timer timer = setTimeout(() => { timer = null }, delay); if (exec) { fn.apply(_self, args) } } else { timer = setTimeout(() => { fn.apply(_self, args) }, delay); } } debounced.remove = function () { clearTimeout(timer) timer = null } return debounced} 函数节流 在n秒内,触发事件,只执行一次事件处理函数 123456789101112131415161718192021222324252627/** * * @param {Function} fn 回调 * @param {Number} delay 延迟时间 * @returns */export function throttle(fn, delay) { var timer = null, begin = new Date().getTime(); return function () { var _self = this, args = arguments, cur = new Date().getTime(); clearTimeout(timer) if (cur - begin > delay) { fn.apply(_self, args) begin = cur } else { timer = setTimeout(() => { fn.apply(_self, args) }, delay); } }}