Debouncing not working

12,158

Your code should look like this

$('input').keyup( function() {
    console.log('k');
});

$('input').keyup(debounce(f, 100));

In your example, you are never calling the function returned and it is always making a new function.


Based on your comment. How to use it in a different context. The following example will write foo 10 times to the console, but will only add one timestamp.

function debounce(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}

function fnc () {
    console.log("Date: ",new Date());
}
var myDebouncedFunction = debounce(fnc, 100);

function foo() {
    console.log("called foo");
    myDebouncedFunction(); 
}

for ( var i=0; i<10; i++) {
    foo();
}
Share:
12,158
Aen Tan
Author by

Aen Tan

Aenism.com

Updated on June 06, 2022

Comments

  • Aen Tan
    Aen Tan about 2 years

    See http://jsfiddle.net/5MvnA/2/ and console.

    There should be less Fs than Ks but there are no Fs at all.

    I got the debouncing code

    function debounce(fn, delay) {
      var timer = null;
      return function () {
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
          fn.apply(context, args);
        }, delay);
      };
    }
    

    from here http://remysharp.com/2010/07/21/throttling-function-calls/

    Mind checking if I'm doing it wrong?

  • Aen Tan
    Aen Tan about 11 years
    I get it. What if I want to use it not with events? Like at teh end of another function? How should I rewrite the debounce function? or is that not possible?
  • Aen Tan
    Aen Tan about 11 years
    F still gets called the same number of times as K, after K. So no debouncing. But this is interesting.
  • Curtis Yallop
    Curtis Yallop almost 10 years
    So: _.debounce returns a function but does not execute it. You must call _.debounce only once. If you want to call your debounced function multiple times, you must store the _.debounce wrapped version of the function and call this stored version. (these were the lessons I learned from this answer that helped me)