diff options
| author | Elizabeth Hunt <elizabeth@simponic.xyz> | 2024-09-07 20:20:07 -0700 |
|---|---|---|
| committer | Elizabeth Hunt <elizabeth@simponic.xyz> | 2024-09-12 17:23:30 -0700 |
| commit | 8ec7f5368232d59f344e1067e1bad5e48dbcb7ae (patch) | |
| tree | 1ad2df4dc00773f2307d1525cc80ac7410ea8fba /static/src/engine/debounce_publisher.ts | |
| parent | e4e31978bae7e45be57b376415a4b925ac8cbc03 (diff) | |
| download | kennel.hatecomputers.club-8ec7f5368232d59f344e1067e1bad5e48dbcb7ae.tar.gz kennel.hatecomputers.club-8ec7f5368232d59f344e1067e1bad5e48dbcb7ae.zip | |
get "cats" up there
Diffstat (limited to 'static/src/engine/debounce_publisher.ts')
| -rw-r--r-- | static/src/engine/debounce_publisher.ts | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/static/src/engine/debounce_publisher.ts b/static/src/engine/debounce_publisher.ts new file mode 100644 index 0000000..8ee4bb0 --- /dev/null +++ b/static/src/engine/debounce_publisher.ts @@ -0,0 +1,46 @@ +export class DebouncePublisher<T> { + private last_event_time = Date.now(); + private unpublished_data: T | undefined; + private interval_id: number | undefined; + + constructor( + private readonly publisher: (data: T) => void | Promise<void>, + private readonly debounce_ms = 100, + ) {} + + public start() { + if (typeof this.interval_id !== "undefined") { + return; + } + this.interval_id = setInterval( + () => this.debounce_publish(), + this.debounce_ms, + ); + } + + public stop() { + if (this.interval_id === null) { + return; + } + clearInterval(this.interval_id); + delete this.interval_id; + } + + public update(data: T) { + this.unpublished_data = data; + this.debounce_publish(); + } + + private debounce_publish() { + if ( + Date.now() - this.last_event_time < this.debounce_ms || + typeof this.unpublished_data === "undefined" + ) { + return; + } + + this.last_event_time = Date.now(); + this.publisher(this.unpublished_data); + this.unpublished_data = undefined; + } +} |
