节流函数
/*** @param {Function} fn 函数* @param {Number} time 时间*/function throttle(fn, time) { let previous = 0 return function() { const now = Date.now() const that = this const args = arguments if (now - previous > time) { fn.apply(that, args) previous = now } }}
防抖函数
/*** @param {Function} fn 函数* @param {Number} time 延迟执行毫秒数* @param {Boolean} immediate true - 立即执行 false - 延迟执行*/function debounce(fn, time = 1000, immediate = true) { let timer return function() { const that = this const args = arguments if (timer) { return clearTimeout(timer) } if (immediate) { const callNow = !timer timer = setTimeout(() => { timer = null }, time) if (callNow) { fn.apply(that, args) } } else { timer = setTimeout(() => { fn.apply(that, args) }, time) } }}