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?