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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Splitting pending and active state lets you enforce a concurrency cap while still accepting unlimited input.
- 2Freeing a slot on dismissal and re-draining keeps the visible count self-regulating without a central scheduler.
- 3Pairing each toast with its timer and element in a Map makes cleanup — clearing timeouts and removing nodes — reliable.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-rate-limited-toast-queue-explained-javascript-3b42/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.