02月08JavaScript函数防抖和节流 发表于 2019-02-08 • 字数统计 1461234567891011121314151617181920function debounce(func, wait, immediate = true) { let timer = 0 return function(...args) { if (timer) { clearTimeout(timer) } else { if (immediate) { func.apply(func, args) } } timer = setTimeout(() => { timer = 0 if (!immediate) { func.apply(func, args) } }, wait) }}12345678910111213141516171819202122232425262728function getNow() { return + new Date()}function throttle(func, wait) { let [now, previous, timer, remainTime] = [0, 0, 0, 0] const later = (...params) => setTimeout(() => { func.apply(func, params) previous = now timer = 0 }, remainTime) return function(...params) { now = getNow() // if if's the first time if (!previous) { previous = now } remainTime = wait - (now - previous) // if there is not a timer, then create it if (!timer) { timer = later(...params) } }}分享到: