I'm trying to write a "debounce" function, and I'm stuck in one segment of the code. In the code below, I pass a callback into addEventListener and I wrap it in a debounce function.
This function will have more functionality later, but for now, I just want it to return a function, that will set a timeout for delay milliseconds and then call the original function with the argument (in this case e).
My problem is on the line in the debounce function that says callback("original-args"). I would like to replace "original-args" with the actual argument that was passed into the callback. How do I get access to that argument?
button.addEventListener("click", debounce(e => {
let elem = document.createElement("P");
elem.textContent = "Clicked";
container.appendChild(elem);
}, 2000))
function debounce(callback, delay) {
return function() {
setTimeout(() => {
callback("original-args")
}, delay)
}
}
You can do something like the following:
button.addEventListener(
"click",
debounce(
(e) => {
let elem = document.createElement("P");
elem.textContent = "Clicked";
container.appendChild(elem);
},
2000
)
);
function debounce(callback, delay) {
return function (...args) {
setTimeout(() => {
callback(...args);
}, delay);
};
}
So you can pass the ...args down to your debounced function. The ...args is a spread operator that means take any number of arguments and store them inside the variable args.