From b98a061d965e8edb06769570fc61b7c45023f18c Mon Sep 17 00:00:00 2001 From: Kuba Orlik Date: Sun, 21 Nov 2021 18:19:58 +0100 Subject: [PATCH] Make render throttled so they don't block the thread --- memory.ts | 17 ++++++++++++++++- util.ts | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/memory.ts b/memory.ts index f9bec5a..95cbfb6 100644 --- a/memory.ts +++ b/memory.ts @@ -1,10 +1,11 @@ import ExtendedRequest from "./extended-request"; -import { getshorthost } from "./util"; +import { getshorthost, makeThrottle } from "./util"; import { EventEmitter } from "events"; import { RequestCluster } from "./request-cluster"; export default class Memory extends EventEmitter { origin_to_history = {} as Record>; + private throttle = makeThrottle(200); async register(request: ExtendedRequest) { await request.init(); console.log("registering request for", request.origin); @@ -34,6 +35,20 @@ export default class Memory extends EventEmitter { ); } + emit(eventName: string, immediate = false) { + try { + if (immediate) { + super.emit(eventName); + return; + } else { + this.throttle(() => super.emit(eventName)); + } + return true; + } catch (e) { + debugger; + } + } + getClustersForOrigin(origin: string): Record { return this.origin_to_history[origin] || {}; } diff --git a/util.ts b/util.ts index 24f80ee..2b5340c 100644 --- a/util.ts +++ b/util.ts @@ -138,3 +138,21 @@ export function toBase64(file: File): Promise { FR.readAsDataURL(file); }); } + +export function makeThrottle(interval: number) { + let last_emit = 0; + function emit(callback: () => void) { + if (Date.now() - last_emit > interval) { + callback(); + last_emit = Date.now(); + return true; + } else { + return false; + } + } + return function (callback: () => void) { + if (!emit(callback)) { + setTimeout(() => emit(callback), interval); + } + }; +}