mirror of
https://gitlab.com/wgp/dougal/software.git
synced 2025-12-06 13:27:08 +00:00
Add throttle() helper.
Useful to avoid repeated updates triggered by incoming row-level database events.
This commit is contained in:
33
lib/www/client/source/src/lib/throttle.js
Normal file
33
lib/www/client/source/src/lib/throttle.js
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* Throttle a function call.
|
||||||
|
*
|
||||||
|
* It delays `callback` by `delay` ms and ignores any
|
||||||
|
* repeated calls from `caller` within at most `maxWait`
|
||||||
|
* milliseconds.
|
||||||
|
*
|
||||||
|
* Used to react to server events in cases where we get
|
||||||
|
* a separate notification for each row of a bulk update.
|
||||||
|
*/
|
||||||
|
function throttle (callback, caller, delay = 100, maxWait = 500) {
|
||||||
|
|
||||||
|
const schedule = async () => {
|
||||||
|
caller.triggeredAt = Date.now();
|
||||||
|
caller.timer = setTimeout(async () => {
|
||||||
|
await callback();
|
||||||
|
caller.timer = null;
|
||||||
|
}, delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!caller.timer) {
|
||||||
|
schedule();
|
||||||
|
} else {
|
||||||
|
const elapsed = Date.now() - caller.triggeredAt;
|
||||||
|
if (elapsed > maxWait) {
|
||||||
|
cancelTimeout(caller.timer);
|
||||||
|
schedule();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
export default throttle;
|
||||||
Reference in New Issue
Block a user