Reputation: 617
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
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