跳过

js的防抖和节流实现

发布时间: at 23:25
本文收录在以下合集中:

当需要限制某个函数被频繁调用时,节流(throttling)和防抖(debouncing)是两种常用的技术。

下面是使用 JavaScript 实现节流和防抖的示例代码:

// 节流函数
function throttle(func, delay) {
  let timeoutId
  let lastExecTime = 0

  return function (...args) {
    const currentTime = Date.now()
    if (currentTime - lastExecTime >= delay) {
      func.apply(this, args)
      lastExecTime = currentTime
    }
  }
}

// 防抖函数
function debounce(func, delay) {
  let timeoutId

  return function (...args) {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

// 测试节流函数
const throttleFn = throttle(() => {
  console.log('Throttled function executed')
}, 1000)

// 测试防抖函数
const debounceFn = debounce(() => {
  console.log('Debounced function executed')
}, 1000)

// 模拟触发函数
setInterval(() => {
  throttleFn()
  debounceFn()
}, 300)

在上面的代码中,throttle 函数会确保被限制的函数在一定时间间隔内只执行一次,而 debounce 函数会在一定时间内延迟函数的执行,如果在延迟时间内再次触发函数,则重新计时。