I am trying to make a debounce function, and I do not understand why it doesn't debounce.
I first created this function here:
const debounce = function throttleFunctionCalls(func, wait, immediate) {
let timeout
return () => {
const context = this
const args = arguments
const later = () => {
timeout = null
if (!immediate) func.apply(context, args)
}
const callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}
const testFunction = () => console.log('test')
setInterval(() => debounce(testFunction(), 10000), 100)
But, it logs every 100ms, so it is not working as intended.
I tried a completely different debounce function, which is arguably better due to spreading args rather than using arguments
, but it suffers the same problem:
function debounce(func, wait) {
let timeout
return function throttleFunctionCalls(...args) {
const context = this
clearTimeout(timeout)
timeout = setTimeout(() => func.apply(context, args), wait)
}
}
const testFunction = () => console.log('test')
setInterval(() => debounce(testFunction(), 10000), 100)
I don't have a real scenario to debounce right now, so I'm having trouble testing it in its natural habitat.
Is there something wrong with the setInterval
approach?
It seems like its awareness of timeout
is getting lost every time. Can anyone shed some light?
[edit]
As charlietfl pointed out in a comment below, I should not be evoking the function. Oops, I definitely shouldn't be doing that, but I tried it before making this question and it didn't work, so for some reason, I ended up with what is above.
function debounce(func, wait) {
let timeout
return function throttleFunctionCalls(...args) {
const context = this
clearTimeout(timeout)
timeout = setTimeout(() => func.apply(context, args), wait)
}
}
const testFunction = (value) => console.log('test: ' + value)
setInterval(() => debounce(testFunction, 1), 100)
This above hangs the thread when I just pass reference function as a reference. I am also uncertain how to pass the actual function arguments into it unless it picks them up by closure.
Can anyone show me a functional example that can pass an arbitrary value in with testFunction()?