Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"setTimeout" VS "debounce" plugin - to defer code execution on events

I want to defer execution of some code on events. What exactly is the difference between using standard setTimeout function and a plugin debounce (link to debounce)?

Here's an example with setTimeout:

var timeout;
$(window).on("scroll", function() {

    clearTimeout(timeout);
    timeout = setTimeout(function() {

        doSomethingFunction();

    }, 500);

});

And here's an example with debounce:

$(window).on("scroll",

    $.debounce(500, doSomethingFunction)

);

Of course with debounce the code is shorter but are there any other benefits? Which one will be faster?

like image 695
zitix Avatar asked Aug 02 '14 11:08

zitix


People also ask

What is the difference between Debounce and setTimeout?

debounce uses setTimeout internally so the difference is related to the number of times setTimeout is fired. debounce throttles the amount of times it fires setTimeout . If multiple requests are sent in a short duration, only one will come through.

Does debounce use setTimeout?

Each time the debounced function is invoked, clear the current pending timeout with clearTimeout() . Use setTimeout() to create a new timeout that delays invoking the function until at least ms milliseconds have elapsed.

Should I use debounce or throttle?

It's simple. They do the exact same thing (rate limiting) except while throttle is being called it'll fire your function periodically, while debounce only fires once at the end. Example: If you're scrolling, throttle will slowly call your function while you scroll (every X milliseconds).

What can I use instead of setTimeout?

later.


1 Answers

debounce uses setTimeout internally so the difference is related to the number of times setTimeout is fired.

debounce throttles the amount of times it fires setTimeout. If multiple requests are sent in a short duration, only one will come through.

var timeout_id = setTimeout(
    debounce_mode ? clear
    : exec, debounce_mode === undefined ? delay - elapsed
    : delay
);

You can review the source code for more information.

The plugin will handle the timeout by setting a timeout id.

like image 77
user3896501 Avatar answered Oct 05 '22 01:10

user3896501