Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Created April 4, 2024 19:50
Show Gist options
  • Save colelawrence/e8f2c36bbf24fc2a03c815e4c0dbe23e to your computer and use it in GitHub Desktop.
Save colelawrence/e8f2c36bbf24fc2a03c815e4c0dbe23e to your computer and use it in GitHub Desktop.
Add items with a throttled effect of applying the items.
/**
* Add items with a throttled effect of applying the items.
* We might use this to collect items and then apply them in batches like for
* search results and timeline items.
*/
export function collectAndFlush<T>(
then: (items: T[]) => void,
// 60 fps
throttleMs: number = 17,
): {
add(item: T): void;
flush(): void;
cancel(): void;
} {
let cancelled = false;
let items: T[] = [];
let timeout: number | null = null;
return {
cancel() {
clearTimeout(timeout);
timeout = null;
cancelled = true;
},
flush() {
if (items.length === 0) return;
if (timeout !== null) {
clearTimeout(timeout);
timeout = null;
}
then(items);
items = [];
},
add(item: T) {
items.push(item);
if (timeout === null) {
timeout = setTimeout(() => {
if (cancelled) return;
then(items);
items = [];
timeout = null;
}, throttleMs);
}
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment