javascript 54 lines · 8 steps

Building a rate-limited toast queue

A queue that caps how many notifications show at once and recycles slots as toasts dismiss.

Explained by highlit
1class ToastQueue {
2 constructor(container, { duration = 4000, max = 3 } = {}) {
3 this.container = container;
4 this.duration = duration;
5 this.max = max;
6 this.active = new Map();
7 this.pending = [];
8 this.seq = 0;
9 }
10 
11 push(message, type = 'info') {
12 const toast = { id: ++this.seq, message, type };
13 this.pending.push(toast);
14 this.drain();
15 return toast.id;
16 }
17 
18 drain() {
19 while (this.active.size < this.max && this.pending.length) {
20 this.render(this.pending.shift());
21 }
22 }
23 
24 render(toast) {
25 const el = document.createElement('div');
26 el.className = `toast toast--${toast.type}`;
27 el.setAttribute('role', 'status');
28 el.textContent = toast.message;
29 el.addEventListener('click', () => this.dismiss(toast.id));
30 
31 const timer = setTimeout(() => this.dismiss(toast.id), this.duration);
32 this.active.set(toast.id, { el, timer });
33 this.container.appendChild(el);
34 requestAnimationFrame(() => el.classList.add('toast--visible'));
35 }
36 
37 dismiss(id) {
38 const entry = this.active.get(id);
39 if (!entry) return;
40 clearTimeout(entry.timer);
41 this.active.delete(id);
42 
43 entry.el.classList.remove('toast--visible');
44 entry.el.addEventListener('transitionend', () => {
45 entry.el.remove();
46 this.drain();
47 }, { once: true });
48 }
49 
50 clear() {
51 this.pending = [];
52 for (const id of [...this.active.keys()]) this.dismiss(id);
53 }
54}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Splitting pending and active state lets you enforce a concurrency cap while still accepting unlimited input.
  2. 2Freeing a slot on dismissal and re-draining keeps the visible count self-regulating without a central scheduler.
  3. 3Pairing each toast with its timer and element in a Map makes cleanup — clearing timeouts and removing nodes — reliable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a rate-limited toast queue — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code