1. 程式人生 > 其它 >JS防抖debounce

JS防抖debounce

js防抖常用封裝

function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 據上一次觸發時間間隔
    const last = +new Date() - timestamp

    // 上次被包裝函式被呼叫時間間隔 last 小於設定時間間隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } 
else { timeout = null // 如果設定為immediate===true,因為開始邊界已經呼叫過了此處無需呼叫 if (!immediate) { result = func.apply(context, args) if (!timeout) context = args = null } } } return function(...args) { context = this timestamp = +new Date() const callNow
= immediate && !timeout // 如果延時不存在,重新設定延時 if (!timeout) timeout = setTimeout(later, wait) if (callNow) { result = func.apply(context, args) context = args = null } return result } }