0

How to make a throttled function reusable?

Created a throttled function, that'd like to re-use in different places in an application. The throttle function should be imported into different file locations!

Bellow, you can find a working version, where the throttle function is used with success (the user can click in both cta and the callbacks are triggered later).

The markup,

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

The script example,

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!'
  })
})

Meanwhile, if we declare a throttled function and try to import it in more then one place, it'll only work for a single case but not concurrently.

For,

export const throttled = throttle(foobar, delay)

I guess that'd common answer is to create a new instance, where imported to, as the following example, that works fine:

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

const throttled = Throttled()

But, what other options are there?

punkbit
  • 7,347
  • 10
  • 55
  • 89
  • You shouldn't use `new` here, but otherwise this is fine. There really isn't another way than to call `throttle` multiple times if you want multiple independent throttling intervals. – Bergi Nov 03 '17 at 13:00
  • @Bergi nice spot! yeah the new keyword was removed now thanks – punkbit Nov 03 '17 at 16:44
  • i do not see this as throttle, instead this is more like a debounce algorithm. – windmaomao Aug 12 '21 at 17:15

0 Answers0