Debounce in JavaScript

Debounce in JavaScript

April 22, 2024

Create a Simple Reusable JavaScript Debounce Function

Code

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 5 seconds'), 5000);
 
handler(); // Will print after 5 seconds

Output

I will print after 5 seconds
logo

It was great having you here, my inbox is always open whether you have a question, a project in mind, or just want to say hi, I'll get back to you!

Available for work

© 2026 Mohd Ubaid Khan. All rights reserved.