Skip to content Skip to sidebar Skip to footer

Is This A Simple Debounce Function In Javascript?

var debounce = function(fn,delay){ var timeoutId; return function debounced(){ if(timeoutId){ clearTimeout(timeoutId); } timeoutId = set

Solution 1:

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

Post a Comment for "Is This A Simple Debounce Function In Javascript?"