8

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?

zitix
  • 810
  • 1
  • 10
  • 26

1 Answers1

12

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.

Kevin Ghadyani
  • 6,829
  • 6
  • 44
  • 62
user3896501
  • 2,987
  • 1
  • 22
  • 25