手写节流函数和防抖函数

节流函数

/**
 * Simple throttle function that executes a passed function only once in the specified timeout
 * @param handlerFunc
 * @param [timeout] the throttle interval
 */
export function throttle(handlerFunc, timeout = 66) {
    
    
  let resizeTimeout
  if (!resizeTimeout) {
    
    
    resizeTimeout = setTimeout(() => {
    
    
      resizeTimeout = null
      handlerFunc()

      // The actualResizeHandler will execute at a rate of 15fps
    }, timeout)
  }
}

防抖函数

// 防抖
export function debounce(func, wait) {
    
    
  let timeout

  return function () {
    
    
    clearTimeout(timeout)
    timeout = setTimeout(func, wait)
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_41886421/article/details/129452285