I build websites for a living, and some things I've been copying from project to project for years. They're all here now: library-free recipes, tools I open every week and all my JavaScript links, sorted.
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.
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. */exportfunction 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`;// }));
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.
*/exportfunction 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. */exportconst 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();// }
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.
*/exportasyncfunction 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) thrownew 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;// }
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.
*/exportasyncfunction 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". */exportfunction nextClick(el) {
const { promise, resolve } = Promise.withResolvers();
el.addEventListener("click", resolve, { once: true });
return promise;
}
// await nextClick(okButton);
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.
*/exportfunction 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");
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.
*/exportfunction 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();// });
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.
*/exportfunction 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 });
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.
*/exportfunction 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]"));
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.
*/exportfunction 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;// });
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.
*/exportfunction 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()));
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)");
exportconst prefersCalm = () => query.matches;
exportfunction onMotionChange(callback) {
const listener = () => callback(query.matches);
query.addEventListener("change", listener);
return () => query.removeEventListener("change", listener);
}
// el.animate(frames, { duration: prefersCalm() ? 0 : 600 });
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.
*/exportfunction 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();
returnnew 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().
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.
*/exportasyncfunction copyText(text) {
try {
await navigator.clipboard.writeText(text);
returntrue;
} catch {
returnfalse;
}
}
// button.addEventListener("click", async () => {// const ok = await copyText(code.textContent);// button.textContent = ok ? "Copied" : "Copy failed";// });
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.
*/exportfunction readParams() {
return Object.fromEntries(new URL(location.href).searchParams);
}
exportfunction 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();
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.
*/exportfunction formToObject(form) {
const data = new FormData(form);
const out = {};
for (const key ofnew 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) });// });
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.
*/exportfunction copyState(state) {
return structuredClone(state);
}
// const draft = structuredClone(saved);// draft.items.push(newItem); // saved is untouched
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. */exportfunction byYear(posts) {
return Object.groupBy(posts, (post) => new Date(post.date).getFullYear());
}
/* Map.groupBy when the keys aren't strings, or the order matters. */exportfunction byLength(words) {
return Map.groupBy(words, (w) => w.length);
}
// byYear([{ date: "2025-03-01" }, { date: "2026-10-17" }])// → { 2025: [ … ], 2026: [ … ] }
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).
*/exportfunction 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),
};
}
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.
*/exportconst 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));
returntrue;
} catch {
returnfalse;
}
},
remove(key) {
try {
localStorage.removeItem(key);
} catch {}
},
};
// const prefs = store.get("prefs", { theme: "dark" });
“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. */exportfunction 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");
}
exportconst euros = (n, lang = navigator.language) =>
new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(n);
exportconst compact = (n, lang = navigator.language) =>
new Intl.NumberFormat(lang, { notation: "compact" }).format(n);
exportconst 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"
fetch with a timeoutfetch never gives up on its own. AbortSignal.timeout gives it a limit and AbortSignal.any joins it with your own cancel button.
View TransitionsAnimates any DOM change: the browser snapshots before and after and blends them. Without support or with reduced motion, it just changes.
Removing listeners with a signalPass the same signal to several addEventListener calls and one abort() removes them all. No more keeping every handler around.
Dates, numbers and lists with Intl“3 days ago”, “1.2K”, “Vue, Svelte and Astro” in the visitor's language, no library. Try the demo in all three languages.