Rana Deep
Rana Deep

Reputation: 617

Is this a simple debounce function in javascript?

var debounce = function(fn,delay){
    var timeoutId;
    return function debounced(){
        if(timeoutId){
            clearTimeout(timeoutId);
        }
        timeoutId = setTimeout(fn.bind(this),delay,arguments);
    }
}

Is the above function a simple way of debouncing ? I want to know if its correctly implemented or not . Are there any flaws ?

Upvotes: 5

Views: 3459

Answers (1)

Bergi
Bergi

Reputation: 664385

Are there any flaws?

Yes. The setTimeout function doesn't take an arguments array as a third parameter. It can take more than two arguments, but those are despised since they're not backwards-compatible with legacy engines. Read on setTimeout at MDN. So better go with

var that = this,
    args = arguments;
timeoutId = setTimeout(function() {
    fn.apply(that, args);
}, delay);

Upvotes: 4

Related Questions