可重复使用的油门功能

时间:2017-11-03 11:48:41

标签: javascript throttling debounce

如何使受限制的函数可重用?

创建了一个限制功能,它希望在应用程序的不同位置重复使用。节流功能应该imported到不同的文件位置!

Bellow,你可以找到一个工作版本,其中成功使用了限制功能(用户可以点击两个cta,稍后会触发回调)。

标记,

  <button id="cta1">cta 1</button>
  <button id="cta2">cta 2</button>

脚本示例

function throttle (fn, delay) {
  let timer = null
  return (args) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn(args)
    }, delay)
  }
}

const foobar1 = throttle(({p1, p2}) => {
  alert(`${p1} ${p2}`)
}, 800)

const foobar2 = throttle(({p1, p2}) => {
  alert(`${p1} ${p2}`)
}, 800)

const btn1 = document.querySelector('#cta1')
const btn2 = document.querySelector('#cta2')

btn1.addEventListener('click', () => {
  foobar1({
    p1: 'hello',
    p2: 'world'
  })
})

btn2.addEventListener('click', () => {
  foobar2({
    p1: 'yo',
    p2: 'cool!'
  })
})

同时,如果我们声明一个限制函数并尝试在多个地方导入它,那么它只能用于单个案例但不能同时工作。

有关,

export const throttled = throttle(foobar, delay)

我猜这个常见的答案是创建一个新实例,其中导入到,如下例所示,可以正常工作:

export const Throttled = function (args) {
  return throttle(foobar, delay)
}

const throttled = Throttled()

但是,还有其他选择吗?

0 个答案:

没有答案