Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a simple debounce function in javascript?

Tags:

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 ?

like image 524
Rana Deep Avatar asked Oct 02 '22 02:10

Rana Deep


1 Answers

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);
like image 125
Bergi Avatar answered Oct 11 '22 03:10

Bergi