I wrote a small debounce utility for an input handler, but when I trigger it several times quickly, it sometimes logs an older value instead of the most recent one. What is wrong with this implementation?
function debounce(fn, wait) {
let timer, lastArgs;
return function (...args) {
lastArgs = args;
if (timer) clearTimeout(timer);
timer = setTimeout(fn(lastArgs), wait);
};
}
const log = debounce((v) => console.log(v), 200);
BayMax