Creating Custom Events
How do you handle event rate limiting and debouncing with custom events?
class RateLimitedEvents {
constructor(limit = 1000) {
this.limit = limit;
this.queue = [];
this.timeout = null;
}
dispatch(eventName, detail) {
this.queue.push({ eventName, detail });
if (!this.timeout) {
this.processQueue();
}
}
processQueue() {
if (this.queue.length === 0) {
this.timeout = null;
return;
}
const { eventName, detail } = this.queue.shift();
const event = new CustomEvent(eventName, { detail });
document.dispatchEvent(event);
this.timeout = setTimeout(
() => this.processQueue(),
this.limit
);
}
}