js.joedoe.dev

recipes

Recipes

Browser JavaScript, nothing to install, that I keep copying from one project to the next. Each recipe is a file: the code you see is the code that runs when you press “Try it”.

Timing and performance#

Debounce#

Waits for the calls to stop and does the work once. I use it in every search box that shows results as you type.

What AI tends to get wrong. It tends to hand you a debounce that drops this and the arguments, or creates it inside the input handler, so every keystroke gets a fresh timer and nothing ever waits.

/* Runs fn once the calls stop for `wait` ms: search boxes, resize, autosave. */
export function debounce(fn, wait = 250) {
	let timer;
	return (...args) => {
		clearTimeout(timer);
		timer = setTimeout(() => fn(...args), wait);
	};
}

// const search = debounce((q) => fetchResults(q), 300);
// input.addEventListener("input", (e) => search(e.target.value));
src/recipes/debounce.js

Throttle with requestAnimationFrame#

Baseline: every browserMDN ↗

At most once per frame, with the latest data. For scroll and pointermove: more often can't be seen and only costs.

What AI tends to get wrong. It suggests a 16 ms setTimeout throttle, or lodash's, for scroll. That drifts out of step with the screen; requestAnimationFrame already means once per frame.

/* At most once per frame, with the latest arguments: scroll, pointermove. */
export function rafThrottle(fn) {
	let frame = 0;
	let last;
	return (...args) => {
		last = args;
		if (frame) return;
		frame = requestAnimationFrame(() => {
			frame = 0;
			fn(...last);
		});
	};
}

// window.addEventListener("pointermove", rafThrottle((e) => {
//   dot.style.translate = `${e.clientX}px ${e.clientY}px`;
// }));
src/recipes/throttle.js

Work for when there's time#

MDN ↗

requestIdleCallback for what can wait, and yielding in long loops so clicks don't hang.

What AI tends to get wrong. It wraps the heavy work in setTimeout(…, 0) and assumes it no longer blocks. That only postpones it: the long loop still freezes clicks.

/*
 * Leave the work that can wait (analytics, prefetch, warming a cache) for
 * when the browser has nothing better to do. setTimeout where it's missing.
 */
export function whenIdle(task, timeout = 2000) {
	if ("requestIdleCallback" in window) {
		return requestIdleCallback(task, { timeout });
	}
	return setTimeout(() => task({ didTimeout: true, timeRemaining: () => 0 }), 1);
}

/* In a long loop, hand the main thread back now and then so clicks still land. */
export const yieldToMain = () =>
	globalThis.scheduler?.yield ? scheduler.yield() : new Promise((r) => setTimeout(r, 0));

// for (const item of bigList) {
//   process(item);
//   if (++n % 200 === 0) await yieldToMain();
// }
src/recipes/idle.js

Network#

fetch with a timeout#

MDN ↗

fetch never gives up on its own. AbortSignal.timeout gives it a limit and AbortSignal.any joins it with your own cancel button.

What AI tends to get wrong. It builds the timeout with Promise.race and a setTimeout: the request isn't cancelled, you just stop waiting, and it keeps using the network. It rarely checks res.ok either.

/*
 * fetch that gives up after `ms`, and that you can also cancel yourself.
 * AbortSignal.any joins both: whichever fires first wins.
 */
export async function getJSON(url, { ms = 8000, signal } = {}) {
	const timeout = AbortSignal.timeout(ms);
	const res = await fetch(url, {
		signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
	});
	if (!res.ok) throw new Error(`HTTP ${res.status}`);
	return res.json();
}

// try {
//   const data = await getJSON("/api/things", { ms: 3000 });
// } catch (err) {
//   if (err.name === "TimeoutError") showRetry();   // too slow
//   else if (err.name === "AbortError") {}          // we cancelled it
//   else throw err;
// }
src/recipes/fetch-timeout.js

Several promises at once#

MDN ↗

allSettled to keep what worked even if something fails, and withResolvers for a promise you resolve from outside.

What AI tends to get wrong. It chains one await after another for things that don't depend on each other, or uses Promise.all where a single failure throws away everything that did work.

/*
 * allSettled: run everything, keep what worked, list what failed,
 * instead of Promise.all throwing away all of it at the first error.
 */
export async function loadAll(urls) {
	const results = await Promise.allSettled(urls.map((u) => fetch(u).then((r) => r.json())));
	return {
		ok: results.filter((r) => r.status === "fulfilled").map((r) => r.value),
		failed: results.flatMap((r, i) => (r.status === "rejected" ? [urls[i]] : [])),
	};
}

/* withResolvers: a promise you resolve from outside, e.g. "wait for this click". */
export function nextClick(el) {
	const { promise, resolve } = Promise.withResolvers();
	el.addEventListener("click", resolve, { once: true });
	return promise;
}

// await nextClick(okButton);
src/recipes/promises.js

Talking between tabs#

Baseline: every browserMDN ↗

BroadcastChannel: log out of every tab at once, or stop the music in one when another starts playing.

What AI tends to get wrong. It reaches for localStorage's storage event to tell other tabs: it writes to disk to send a message, and it never reaches the tab that sent it.

/*
 * Talk between tabs of the same site: log out everywhere, sync a cart,
 * stop a player when another tab starts one. Same name, same channel.
 */
export function channel(name, onMessage) {
	const bc = new BroadcastChannel(name);
	bc.addEventListener("message", (event) => onMessage(event.data));
	return {
		send: (data) => bc.postMessage(data),
		close: () => bc.close(),
	};
}

// const session = channel("session", (msg) => msg === "logout" && location.reload());
// logoutButton.onclick = () => session.send("logout");
src/recipes/broadcast.js

DOM and events#

Event delegation#

Baseline: every browserMDN ↗

One listener on the parent instead of one per button. Works for whatever you add later too.

What AI tends to get wrong. It adds a listener to every list item inside a forEach, so items added later get none. Or it checks e.target without closest() and misses clicks on the icon inside.

/*
 * One listener on the parent instead of one per button. Works for items
 * added later, too. closest() finds the button even if you click its icon.
 */
export function delegate(root, type, selector, handler) {
	const listener = (event) => {
		const match = event.target.closest(selector);
		if (match && root.contains(match)) handler(event, match);
	};
	root.addEventListener(type, listener);
	return () => root.removeEventListener(type, listener);
}

// delegate(list, "click", "[data-remove]", (event, button) => {
//   button.closest("li").remove();
// });
src/recipes/delegation.js

Removing listeners with a signal#

Baseline: every browserMDN ↗

Pass the same signal to several addEventListener calls and one abort() removes them all. No more keeping every handler around.

What AI tends to get wrong. It passes an arrow function to addEventListener and then an “identical” arrow to removeEventListener: it isn't the same function, so nothing is removed.

/*
 * Remove a whole bunch of listeners at once: give them the same signal and
 * abort it. No need to keep references to every handler.
 */
export function bindDrag(el, onMove) {
	const controller = new AbortController();
	const { signal } = controller;
	el.addEventListener("pointerdown", () => {
		window.addEventListener("pointermove", onMove, { signal });
		window.addEventListener("pointerup", () => controller.abort(), { once: true, signal });
	}, { once: true, signal });
	return () => controller.abort();
}

// { once: true } alone removes a listener after its first call:
// dialog.addEventListener("close", cleanUp, { once: true });
src/recipes/listeners-signal.js

Reveal on scroll#

Baseline: every browserMDN ↗

IntersectionObserver marks what comes into view and stops watching it. Same pattern to lazy-load images or videos.

What AI tends to get wrong. It listens to scroll and calls getBoundingClientRect on every event, forcing layout dozens of times a second. And it never stops observing what has already appeared.

/*
 * Adds .is-in when an element enters the screen, once, and stops watching it.
 * Same pattern for lazy anything: swap data-src for src inside the callback.
 */
export function reveal(elements, { rootMargin = "0px 0px -10% 0px" } = {}) {
	const io = new IntersectionObserver(
		(entries) => {
			for (const entry of entries) {
				if (!entry.isIntersecting) continue;
				entry.target.classList.add("is-in");
				io.unobserve(entry.target);
			}
		},
		{ rootMargin },
	);
	for (const el of elements) io.observe(el);
	return () => io.disconnect();
}

// reveal(document.querySelectorAll("[data-reveal]"));
src/recipes/reveal.js

An element's size#

Baseline: every browserMDN ↗

ResizeObserver tells you when a box changes size, not the window. For canvases and charts that must redraw.

What AI tends to get wrong. It listens to window resize to learn an element's size. It misses changes from content or a sidebar opening; it only hears the window.

/*
 * Calls back with an element's own size whenever it changes, not the
 * window's. For canvases, charts, or anything a container query can't do.
 */
export function onResize(el, callback) {
	const ro = new ResizeObserver(([entry]) => {
		const { inlineSize: width, blockSize: height } = entry.contentBoxSize[0];
		callback({ width, height });
	});
	ro.observe(el);
	return () => ro.disconnect();
}

// onResize(canvas.parentElement, ({ width, height }) => {
//   canvas.width = width * devicePixelRatio;
//   canvas.height = height * devicePixelRatio;
// });
src/recipes/resize.js

Interface#

View Transitions#

Baseline: newly availableMDN ↗

Animates any DOM change: the browser snapshots before and after and blends them. Without support or with reduced motion, it just changes.

What AI tends to get wrong. It calls document.startViewTransition without checking it exists, so older browsers throw. It rarely respects prefers-reduced-motion either.

/*
 * Animates any DOM change: the browser snapshots before and after and
 * crossfades. Without support, or with reduced motion, it just changes.
 */
export function transition(update) {
	const calm = matchMedia("(prefers-reduced-motion: reduce)").matches;
	if (!document.startViewTransition || calm) {
		update();
		return Promise.resolve();
	}
	return document.startViewTransition(update).finished;
}

// Give each moving item its own name and they glide to their new place:
// li.style.viewTransitionName = `item-${id}`;
// transition(() => list.append(...[...list.children].reverse()));
src/recipes/view-transition.js

Respecting reduced motion#

Baseline: every browserMDN ↗

CSS has a media query; JS needs matchMedia, and listening for the change, because some people switch it mid-visit.

What AI tends to get wrong. It reads matchMedia(…).matches once on load and that's it. If the person changes the setting while the page is open, it never notices.

/*
 * Ask before animating from script. CSS has its media query; JS needs
 * matchMedia, and the change event, because people switch it mid-visit.
 */
const query = matchMedia("(prefers-reduced-motion: reduce)");

export const prefersCalm = () => query.matches;

export function onMotionChange(callback) {
	const listener = () => callback(query.matches);
	query.addEventListener("change", listener);
	return () => query.removeEventListener("change", listener);
}

// el.animate(frames, { duration: prefersCalm() ? 0 : 600 });
src/recipes/reduced-motion.js

A confirm() with <dialog>#

Baseline: every browserMDN ↗

A real <dialog> brings the focus trap, Esc and the backdrop for free. Wrapped in a promise it's a confirm() that looks like your site.

What AI tends to get wrong. It builds you a modal from a div, a backdrop and z-index: 9999. Without <dialog> there's no focus trap, no Esc and the rest of the page isn't inert.

/*
 * A confirm() that looks like your site: a real <dialog> with focus trap,
 * Esc and the backdrop for free. Resolves with the button's value.
 */
export function ask(message, { yes = "OK", no = "Cancel" } = {}) {
	const dialog = document.createElement("dialog");
	const form = document.createElement("form");
	form.method = "dialog";
	const text = document.createElement("p");
	text.textContent = message;
	const cancel = Object.assign(document.createElement("button"), { value: "no", textContent: no });
	const accept = Object.assign(document.createElement("button"), { value: "yes", textContent: yes });
	form.append(text, cancel, accept);
	dialog.append(form);
	document.body.append(dialog);
	dialog.showModal();
	return new Promise((resolve) => {
		dialog.addEventListener("close", () => {
			resolve(dialog.returnValue === "yes");
			dialog.remove();
		}, { once: true });
	});
}

// Lighter menus and tips need no JS at all: popover="auto" + popovertarget.
// From script: menu.showPopover(), menu.hidePopover(), menu.togglePopover().
src/recipes/dialog.js

Copy button#

Baseline: every browserMDN ↗

navigator.clipboard needs https and a user gesture. It returns whether it worked so the button doesn't lie.

What AI tends to get wrong. It still reaches for document.execCommand('copy') with a hidden textarea, which is deprecated. Or it uses navigator.clipboard with no catch, so on failure the button just goes quiet.

/*
 * The copy button. Needs https (or localhost) and a click or key press;
 * it says whether it worked so the button can tell the truth.
 */
export async function copyText(text) {
	try {
		await navigator.clipboard.writeText(text);
		return true;
	} catch {
		return false;
	}
}

// button.addEventListener("click", async () => {
//   const ok = await copyText(code.textContent);
//   button.textContent = ok ? "Copied" : "Copy failed";
// });
src/recipes/clipboard.js

Data and state#

Filters in the URL#

Baseline: every browserMDN ↗

Keep the search in the address bar: a reload or a shared link opens the same view. replaceState so history doesn't fill up.

What AI tends to get wrong. It builds the query string by hand, concatenating, with no encodeURIComponent: an “&” in a filter breaks it. And it calls pushState on every keystroke, flooding history.

/*
 * Keep filters in the address bar, so a reload or a shared link opens the
 * same view. replaceState: no new history entry per keystroke.
 */
export function readParams() {
	return Object.fromEntries(new URL(location.href).searchParams);
}

export function setParam(key, value) {
	const url = new URL(location.href);
	if (value === "" || value == null) url.searchParams.delete(key);
	else url.searchParams.set(key, value);
	history.replaceState(null, "", url);
}

// setParam("q", input.value);   // ?q=gsap
// const { q = "" } = readParams();
src/recipes/url-params.js

A form to an object#

Baseline: every browserMDN ↗

FormData reads the whole form at once, no field by field. Repeated checkboxes come out as a list.

What AI tends to get wrong. It reads each field with querySelector(…).value, one per line, and forgets unchecked checkboxes and multi-selects.

/*
 * A form straight into an object, no field-by-field. Checkbox groups and
 * multiple selects come back as arrays thanks to getAll.
 */
export function formToObject(form) {
	const data = new FormData(form);
	const out = {};
	for (const key of new Set(data.keys())) {
		const values = data.getAll(key);
		out[key] = values.length > 1 ? values : values[0];
	}
	return out;
}

// form.addEventListener("submit", async (e) => {
//   e.preventDefault();
//   await fetch(form.action, { method: "POST", body: new FormData(form) });
// });
src/recipes/form-data.js

Deep copy#

Baseline: every browserMDN ↗

structuredClone makes a real copy and, unlike the JSON trick, keeps Dates, Maps, Sets and circular references.

What AI tends to get wrong. It almost always suggests JSON.parse(JSON.stringify(x)): dates come back as strings, and Map, Set and undefined vanish without a word.

/*
 * A real deep copy, built in. Unlike JSON.parse(JSON.stringify(x)) it keeps
 * Dates, Maps, Sets, typed arrays and circular references.
 * It can't copy functions, DOM nodes or class instances' methods.
 */
export function copyState(state) {
	return structuredClone(state);
}

// const draft = structuredClone(saved);
// draft.items.push(newItem);   // saved is untouched
src/recipes/structured-clone.js

Grouping with Object.groupBy#

MDN ↗

The reduce I wrote by hand every week, now built in. Map.groupBy when the keys aren't strings.

What AI tends to get wrong. It writes a six-line reduce with a hand-initialised accumulator, or imports lodash's groupBy, when Object.groupBy is in every browser now.

/* Object.groupBy: the reduce I used to write by hand every week. */
export function byYear(posts) {
	return Object.groupBy(posts, (post) => new Date(post.date).getFullYear());
}

/* Map.groupBy when the keys aren't strings, or the order matters. */
export function byLength(words) {
	return Map.groupBy(words, (w) => w.length);
}

// byYear([{ date: "2025-03-01" }, { date: "2026-10-17" }])
// → { 2025: [ … ], 2026: [ … ] }
src/recipes/group-by.js

Arrays without mutating#

Baseline: every browserMDN ↗

toSorted, toReversed, with and toSpliced return a copy. Ideal for state you mustn't touch, like in Vue or an undo stack.

What AI tends to get wrong. It calls sort() or reverse() on the state's array to render a sorted list: that changes it in place and the original is altered.

/*
 * The array methods that return a new array instead of changing the old one.
 * Good with state you must not mutate (Vue, React, undo history).
 */
export function arrays(list) {
	return {
		sorted: list.toSorted((a, b) => a - b),   // sort() without touching list
		reversed: list.toReversed(),
		replaced: list.with(0, 99),               // list[0] = 99, as a copy
		removed: list.toSpliced(1, 1),
		last: list.at(-1),                        // no more list[list.length - 1]
		lastBig: list.findLast((n) => n > 2),
	};
}
src/recipes/arrays.js

localStorage without surprises#

Baseline: every browserMDN ↗

localStorage can throw (private mode, full, blocked cookies) and only holds strings. Wrap it once and the rest of the code stops worrying.

What AI tends to get wrong. It does a bare JSON.parse(localStorage.getItem(…)): one corrupt value, or a browser that blocks storage, throws and the app won't start.

/*
 * localStorage can throw (private mode, full, blocked cookies) and only
 * holds strings. Wrapped once, the rest of the code stops worrying.
 */
export const store = {
	get(key, fallback = null) {
		try {
			const raw = localStorage.getItem(key);
			return raw === null ? fallback : JSON.parse(raw);
		} catch {
			return fallback;
		}
	},
	set(key, value) {
		try {
			localStorage.setItem(key, JSON.stringify(value));
			return true;
		} catch {
			return false;
		}
	},
	remove(key) {
		try {
			localStorage.removeItem(key);
		} catch {}
	},
};

// const prefs = store.get("prefs", { theme: "dark" });
src/recipes/storage.js

Languages#

Dates, numbers and lists with Intl#

Baseline: every browserMDN ↗

“3 days ago”, “1.2K”, “Vue, Svelte and Astro” in the visitor's language, no library. Try the demo in all three languages.

What AI tends to get wrong. It formats dates with getDate() + '/' + (getMonth() + 1) and numbers with toFixed(2) and a replace on the dot. It comes out in one language and wrong in the rest.

/* Dates, numbers and lists in the visitor's language, no library. */

export function timeAgo(date, lang = navigator.language) {
	const rtf = new Intl.RelativeTimeFormat(lang, { numeric: "auto" });
	const seconds = (date.getTime() - Date.now()) / 1000;
	const steps = [
		["year", 31536000],
		["month", 2592000],
		["week", 604800],
		["day", 86400],
		["hour", 3600],
		["minute", 60],
	];
	for (const [unit, size] of steps) {
		if (Math.abs(seconds) >= size) return rtf.format(Math.round(seconds / size), unit);
	}
	return rtf.format(Math.round(seconds), "second");
}

export const euros = (n, lang = navigator.language) =>
	new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(n);

export const compact = (n, lang = navigator.language) =>
	new Intl.NumberFormat(lang, { notation: "compact" }).format(n);

export const list = (items, lang = navigator.language) =>
	new Intl.ListFormat(lang, { type: "conjunction" }).format(items);

// timeAgo(new Date(Date.now() - 3 * 86400e3), "es")  → "hace 3 días"
// list(["Vue", "Svelte", "Astro"], "ca")             → "Vue, Svelte i Astro"
src/recipes/intl.js

↑↓ move · ↵ open · esc close