0

When I run this code, I don't see any console log in the console. Is the debounce method (taken from here) not executing the method at all?

function debounce(func, wait, immediate) {
    var timeout;
    var args = Array.prototype.slice.call(arguments, 3);
    return function () {
        var context = this;
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            timeout = null;
            if (!immediate) {
                func.apply(context, args);
            }
        }, wait);
        if (callNow) func.apply(context, args);
    };
};

var f1 = function(){ console.log(1) }; 
var f2 = function(){ console.log(2) };  
debounce( f1, 100, false ); 
debounce( f2, 100, false );    

Is this the expected behavior or did I missed something here?

Community
  • 1
  • 1
gurvinder372
  • 66,980
  • 10
  • 72
  • 94

1 Answers1

3

That's because your debounce function returns another function. You have to call it like this:

debounce( f1, 100, false )(); 
debounce( f2, 100, false )(); 

function debounce(func, wait, immediate) {
    var timeout;
    var args = Array.prototype.slice.call(arguments, 3);
    return function () {
        var context = this;
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            timeout = null;
            if (!immediate) {
                func.apply(context, args);
            }
        }, wait);
        if (callNow) func.apply(context, args);
    };
};

var f1 = function(){ console.log(1) }; 
var f2 = function(){ console.log(2) };  
debounce( f1, 100, false )(); 
debounce( f2, 100, false )();    
Erazihel
  • 7,295
  • 6
  • 30
  • 53