Debouncing not working

Aen Tan picture Aen Tan · May 22, 2013 · Viewed 11.9k times · Source

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?

Answer

epascarello picture epascarello · May 22, 2013

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();
}