Debounce in JavaScript

๐Ÿ“† ยท
const debounce = (func, duration = 2000) => {
let timeout;
return function (...args) {
const effect = () => {
timeout = null;
return func.apply(this, args);
};
clearTimeout(timeout);
timeout = setTimeout(effect, duration);
};
};
export default debounce;

Usage

import debounce from 'utils/debounce';
const handler = debounce(
() => console.log('I will print after 4 seconds'),
4000,
);

Output

Output for debounce
Output for debounce