Debounce in Javascript




How to write Debounce function in pure javaScript. Without using lodash, underscore or any external library. For click , scroll or mouse move events.

#javaScript #debounce #function

*My Udemy Courses
https://www.udemy.com/js-masterclass/
https://www.udemy.com/course/react-hooks-course/

Follow me for technology updates
* https://facebook.com/techsith
* https://www.facebook.com/groups/techsith
* https://twitter.com/techsith1
* https://www.linkedin.com/groups/13677140/
* https://medium.com/@patelhemil

Help me translate this video.
* https://www.youtube.com/timedtext_cs_panel?c=UCbGZKLIHpox2l0whz6_RYyg&tab=2
Note: use https://translate.google.com/ to translate this video to your language. Let me know once you do that so i can give you credit. Thank you in advance.

Original source


29 responses to “Debounce in Javascript”

  1. I've always used lodash.debounce without thinking about it, thanks for explaining how debounce works by building out a debounce function from scratch. Also, I've been relying on loading prop provided by UI libraries, in Ant Design, you could do <Button loading={loadingData}>Click</Button>, here loadingData is a state in React component, once loadingData is true, the button will automatically stop listening click event. During one code review, a senior told me to use debounce anyway since it's more secure. he thinks there's still a chance loading prop isn't 100% in sync with the loadingData state, at least not in real time. I guess he's right

  2. Why don't we do something like this?

    let timer;
    function debounceTwo() {
    if (timer) {
    clearTimeout(timer);
    timer = setTimeout(() => { heavyFunctionCall() }, 200)
    }
    else {
    timer = setTimeout(() => { heavyFunctionCall() }, 200)
    }
    }

    Please clarify!!

  3. Practically we need to do the action first then debounce. Following snippet is an improvement which could be useful in many other scenarios – https://gist.github.com/abhaystoic/1cb2e7464ba2610c4aa449cc006e6b14

    const debounce = (func, delay) => {
    let stop = false;
    return (…args) => {
    if (stop){
    setTimeout(() => {
    stop = false;
    }, 2000);
    }
    else {
    func(…args);
    stop = true;
    }
    };
    };

    document.getElementById('myID').addEventListener('click', debounce((e) => console.log('Clicked!!!'), 2000));

  4. Thanks sir for demonstrate us with example 🙂.. but as far as I know, on the shopping cart button, we can also use the throttling instead of debounce because in case of throttling, only initial click action will be execute and other action execute only after delay period.

  5. Thank you for sharing us this practical application; for my understanding, we basically created a self removed timer (debounce) and use it to control the multiple events. like this idea!

Leave a Reply