Skip to content

Instantly share code, notes, and snippets.

@abezhinaru
Last active January 24, 2018 17:15
Show Gist options
  • Save abezhinaru/37bfceb6aa2f564b12519e32b679ee08 to your computer and use it in GitHub Desktop.
Save abezhinaru/37bfceb6aa2f564b12519e32b679ee08 to your computer and use it in GitHub Desktop.
const debounce = (func, waitTime) => {
let startTime;
let timeoutId;
let isWorking = () => {
return timeoutId && startTime + waitTime > Date.now();
}
return () => {
if (isWorking()) {
clearInterval(timeoutId);
}
startTime = Date.now();
timeoutId = setTimeout(() => {
func.apply(this, arguments);
}, waitTime);
}
}
export {
Debounce
};
@pkolomeitsev
Copy link

The arguments you are sending the callback are not available in setTimeout(). This should solve this:

return (...args) => {
        if (isWorking()) {
            clearInterval(timeoutId);
        }

        startTime = Date.now();

        timeoutId = setTimeout(() => {
                func(...args);
        }, waitTime);
    }

😸

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment