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
import { useDeferredValue, useMemo, useState } from "react"; function ProductSearch({ products }) { const [query, setQuery] = useState("");
Keeping search input snappy with useDeferredValue in React
concurrent-rendering
deferred-value
memoization
Intermediate
7 steps
javascript
const IBAN_LENGTHS = { DE: 22, FR: 27, GB: 22, ES: 24, IT: 27, NL: 18, BE: 16, CH: 21, AT: 20, PT: 25, };
How IBAN validation works in JavaScript
validation
checksum
modular-arithmetic
Intermediate
8 steps
javascript
import { useCallback, useState } from "react"; const MIN = 0; const MAX = 1000;
Building a dual-thumb price slider in React
controlled-components
state-clamping
usecallback
Intermediate
8 steps
javascript
class LyricsSync { constructor(audio, container, lines) { this.audio = audio; this.container = container;
Building a synced lyrics highlighter
binary-search
dom-manipulation
event-handling
Intermediate
9 steps
javascript
const express = require('express'); const app = express();
Enforcing HTTPS with Express middleware
middleware
https
security
Intermediate
6 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 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.