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); + } + }; +}