James White
James White

Reputation: 43

Debounce function running multiple time after timeout complete

I am trying to run a debounce function that take the input of "SaveValue" which would take the value of the input and save that some where. Problem is it runs the "SaveValue" function multiple time one the debounce timeout in complete. I have many of these input and don't really want to be putting a bunch of onEventListeners through out the code. What is the best way to make this work.

<input id="testInput" onkeyup="debounce(() => { SaveValue(value, 'savehere', 'onhere') } , 300)();" type="text" /> 
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
function SaveValue(value1, value2, value3){
    console.log(`Save value of ${value1} here -> ${value2} on field -> ${value3}`);
}

Upvotes: 2

Views: 185

Answers (2)

James White
James White

Reputation: 43

After playing around with this I have figured a way to make this re-useable. Thankyou Lloyd for clearing this up for me. Works great.

<input onkeyup="dSaveValue(value, 'DatabaseTable', 'DatabaseRow')" type="text" />
<input onkeyup="dSaveValue(value, 'DatabaseTable', 'DifferentDatabaseRow')" type="text" />
const dSaveValue = debounce((value1, value2, value3) => { SaveValue(value1, value2, value3)}, 1000, false)

Upvotes: 1

Lloyd
Lloyd

Reputation: 256

I have done a little testing on your code, and it seems the way the debounce function is being called in the onkeyup handler, is creating a new instance of the function call (and subsequently a new timer) for every event. This would result in the multiple calls.

Try changing it to something like this:

const dSaveValue = debounce(() => { SaveValue("value", 'savehere', 'onhere')}, 1000, false)

<input id="testInput" onkeyup="dSaveValue()" type="text" />

Lloyd

Upvotes: 1

Related Questions