Last active
July 17, 2017 18:49
-
-
Save jeromepl/dac1d1a0f877e3a2b77c152b3473fa74 to your computer and use it in GitHub Desktop.
Debouncer that keeps the last N calls active
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Keep the last N calls active | |
// A regular debounce function would only keep a single function call | |
// on timeout at a time. | |
function debounceGroup(func, wait, groupSize) { | |
var timeouts = []; // Use this array as a queue of method calls | |
return function() { | |
var context = this, | |
args = Array.prototype.slice.call(arguments, 0); | |
if (timeouts.length >= groupSize) | |
clearTimeout(timeouts.shift()); | |
timeouts.push(setTimeout(function() { | |
func.apply(context, args); | |
}, wait)); | |
}; | |
} | |
// If you need a varying group size: | |
function debounceGroupVarying(func, wait) { | |
var timeouts = []; | |
return function(groupSize) { // n is now passed as the first argument to the function 'func' | |
var context = this, | |
args = Array.prototype.slice.call(arguments, 1), | |
removedTimeouts = timeouts.splice(0, timeouts.length - groupSize + 1); | |
for (var i = 0; i < removedTimeouts.length; i++) | |
clearTimeout(removedTimeouts[i]); | |
timeouts.push(setTimeout(function() { | |
func.apply(context, args); | |
}, wait)); | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Debounce a group of 4 method calls with a 200ms wait time | |
var debouncedLog = debounceGroup(function (someVar) { | |
console.log(someVar); | |
}, 200, 4); | |
for (var i = 0; i < 10; i++) | |
debouncedLog(i); // Prints only 6, 7, 8, 9 | |
// ...and to have a debounced method with a varying group size: | |
// Note that the following is not a really good example since it | |
// essentially does the same as debounceGroup(). | |
debouncedLog = debounceGroupVarying(function (someVar) { | |
console.log(someVar); | |
}, 200); | |
for (var i = 0; i < 10; i++) | |
debouncedLog(3, i); // Prints only 7, 8, 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment