Skip to content

Commit

Permalink
Add comments and avoid Array.fill
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinpschaaf committed Feb 27, 2019
1 parent e8c24ff commit 567c10b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
4 changes: 4 additions & 0 deletions lib/utils/debounce.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ let debouncerQueue = new Set();
* @return {void}
*/
export const enqueueDebouncer = function(debouncer) {
// Re-enqueued debouncers are put at the end of the queue; for Set, this
// means removing and re-adding, since forEach traverses insertion order
if (debouncerQueue.has(debouncer)) {
debouncerQueue.delete(debouncer);
}
Expand All @@ -136,6 +138,8 @@ export const enqueueDebouncer = function(debouncer) {
*/
export const flushDebouncers = function() {
const didFlush = Boolean(debouncerQueue.size);
// If new debouncers are added while flushing, Set.forEach will ensure
// newly added ones are also flushed
debouncerQueue.forEach(debouncer => {
try {
debouncer.flush();
Expand Down
24 changes: 15 additions & 9 deletions test/unit/debounce.html
Original file line number Diff line number Diff line change
Expand Up @@ -217,16 +217,22 @@
const timeoutCallback = sinon.spy(() => actualCallbacks.push(timeoutCallback));
enqueueDebouncer(Debouncer.debounce(null, timeOut, timeoutCallback));
// Set of short-running debouncers enqueued in the middle of first set
const nestedCallbacks = new Array(150).fill().map((_, i) => sinon.spy(() =>
actualCallbacks.push(nestedCallbacks[i])));
const nestedCallbacks = [];
for (let i=0; i<150; i++) {
nestedCallbacks.push(sinon.spy(() =>
actualCallbacks.push(nestedCallbacks[i])));
}
// First set of short-running debouncers
const microtaskCallbacks = new Array(150).fill().map((_, i) => sinon.spy(() => {
actualCallbacks.push(microtaskCallbacks[i]);
if (i === 125) {
nestedCallbacks.forEach(cb =>
enqueueDebouncer(Debouncer.debounce(null, microTask, cb)));
}
}));
const microtaskCallbacks = [];
for (let i=0; i<150; i++) {
microtaskCallbacks.push(sinon.spy(() => {
actualCallbacks.push(microtaskCallbacks[i]);
if (i === 125) {
nestedCallbacks.forEach(cb =>
enqueueDebouncer(Debouncer.debounce(null, microTask, cb)));
}
}));
}
microtaskCallbacks.forEach(cb =>
enqueueDebouncer(Debouncer.debounce(null, microTask, cb)));
// Expect short before long
Expand Down

0 comments on commit 567c10b

Please sign in to comment.