Code library
Free snippets & functions
Copy, adapt and use them in your own projects.
async function runLimited(items, limit, worker) {
const results = new Array(items.length);
let next = 0;
async function lane() {
while (next < items.length) {
const i = next++;
results[i] = await worker(items[i], i);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, lane));
return results;
}
// Example: fetch 20 URLs, 3 at a time
// const pages = await runLimited(urls, 3, (u) => fetch(u).then((r) => r.text()));Promise.all starts everything at once. This helper runs the same list with a limit (for example 3 downloads at a time).
function onScrollFrame(callback) {
let ticking = false;
window.addEventListener('scroll', () => {
if (ticking) return;
ticking = true;
requestAnimationFrame(() => {
callback(window.scrollY);
ticking = false;
});
}, { passive: true });
}
onScrollFrame((y) => {
document.body.classList.toggle('scrolled', y > 80);
});Collect scroll events and do the work at most once per screen refresh.
const KEY = 'outbox';
const read = () => JSON.parse(localStorage.getItem(KEY) || '[]');
const write = (q) => localStorage.setItem(KEY, JSON.stringify(q));
async function send(url, data) {
if (!navigator.onLine) { write([...read(), { url, data }]); return { queued: true }; }
try {
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
} catch {
write([...read(), { url, data }]);
return { queued: true };
}
}
async function flush() {
const queue = read();
write([]);
for (const job of queue) await send(job.url, job.data);
}
window.addEventListener('online', flush);Save failed or offline POSTs and send them again when the connection returns.
function timeIt(label, fn) {
performance.mark(label + ':start');
const result = fn();
performance.mark(label + ':end');
performance.measure(label, label + ':start', label + ':end');
const ms = performance.getEntriesByName(label).at(-1).duration;
console.log(`${label}: ${ms.toFixed(1)} ms`);
return result;
}
timeIt('sort', () => Array.from({ length: 100000 }, (_, i) => (i * 7919) % 10007).sort((a, b) => a - b));
new PerformanceObserver((list) => list.getEntries().forEach((e) => console.log('LCP', e.startTime)))
.observe({ type: 'largest-contentful-paint', buffered: true });performance.now() and marks give precise timings. Log them, then fix what is really slow.
const list = document.querySelector('#sortable');
let dragging = null;
list.addEventListener('dragstart', (e) => {
dragging = e.target.closest('li');
e.dataTransfer.effectAllowed = 'move';
dragging.classList.add('dragging');
});
list.addEventListener('dragover', (e) => {
e.preventDefault();
const over = e.target.closest('li');
if (over && over !== dragging) {
const after = e.clientY > over.getBoundingClientRect().top + over.offsetHeight / 2;
over.parentNode.insertBefore(dragging, after ? over.nextSibling : over);
}
});
list.addEventListener('dragend', () => {
dragging.classList.remove('dragging');
const order = [...list.children].map((li) => li.dataset.id); // send this to the server
console.log(order);
});
// <ul id="sortable"><li draggable="true" data-id="1">One</li>...</ul>Native HTML5 drag and drop. Save the new order with the item ids after the drop.
function infiniteScroll({ list, sentinel, loadPage }) {
let page = 0, loading = false, done = false;
const io = new IntersectionObserver(async ([entry]) => {
if (!entry.isIntersecting || loading || done) return;
loading = true;
try {
const items = await loadPage(++page);
if (!items.length) { done = true; io.disconnect(); }
list.append(...items.map((t) => Object.assign(document.createElement('li'), { textContent: t })));
} finally {
loading = false;
}
}, { rootMargin: '400px' });
io.observe(sentinel);
return io;
}Watch an element at the end of the list. When it appears, load the next page.
function trapFocus(dialog) {
const focusable = () => [...dialog.querySelectorAll('a[href], button:not([disabled]), input, select, textarea, [tabindex]:not([tabindex="-1"])')];
const opener = document.activeElement;
function onKey(e) {
if (e.key === 'Escape') { release(); dialog.hidden = true; return; }
if (e.key !== 'Tab') return;
const items = focusable();
const first = items[0], last = items[items.length - 1];
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
}
dialog.addEventListener('keydown', onKey);
focusable()[0]?.focus();
function release() { dialog.removeEventListener('keydown', onKey); opener?.focus(); }
return release;
}Tab and Shift+Tab stay inside the open dialog, and focus returns to the button that opened it.
function readState() {
return Object.fromEntries(new URLSearchParams(location.search));
}
function writeState(patch, { replace = false } = {}) {
const params = new URLSearchParams(location.search);
for (const [k, v] of Object.entries(patch)) {
v === '' || v == null ? params.delete(k) : params.set(k, v);
}
const url = location.pathname + (params.size ? '?' + params : '') + location.hash;
history[replace ? 'replaceState' : 'pushState']({}, '', url);
}
window.addEventListener('popstate', () => console.log('state is now', readState()));
writeState({ q: 'php', page: 2 });Shareable links and a working Back button: write the state to the address, and read it back.
const machine = {
draft: { submit: 'review' },
review: { approve: 'published', reject: 'draft' },
published: { archive: 'archived' },
archived: {},
};
function transition(state, action) {
const next = machine[state]?.[action];
if (!next) throw new Error(`Cannot ${action} from ${state}`);
return next;
}
let s = 'draft';
s = transition(s, 'submit'); // review
s = transition(s, 'approve'); // publishedList which moves are allowed, and impossible states can no longer happen.
class History {
#past = [];
#future = [];
constructor(initial) { this.state = initial; }
push(next) {
this.#past.push(this.state);
this.state = next;
this.#future = [];
}
undo() {
if (!this.#past.length) return this.state;
this.#future.push(this.state);
return (this.state = this.#past.pop());
}
redo() {
if (!this.#future.length) return this.state;
this.#past.push(this.state);
return (this.state = this.#future.pop());
}
get canUndo() { return this.#past.length > 0; }
get canRedo() { return this.#future.length > 0; }
}
const h = new History('a');
h.push('b'); h.push('c');Two stacks: what you can undo and what you can redo. Any new change clears the redo stack.
function debounceAsync(fn, wait = 300) {
let timer, latest = 0;
return (...args) => new Promise((resolve) => {
clearTimeout(timer);
const id = ++latest;
timer = setTimeout(async () => {
const result = await fn(...args);
if (id === latest) resolve(result); // ignore answers that are no longer the newest
}, wait);
});
}
const search = debounceAsync(async (q) => 'results for ' + q, 20);
const first = search('a');
const second = search('ab');Calls made too fast are skipped, and old slow answers can never overwrite newer ones.
async function sha256(text) {
const bytes = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest('SHA-256', bytes);
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
// await sha256('hello') -> '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'Built into the browser. Needs HTTPS. Do not use a plain hash to store passwords: that is a job for the server.
const loaded = new Map();
function loadScript(src, attrs = {}) {
if (loaded.has(src)) return loaded.get(src);
const p = new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = src;
s.async = true;
Object.assign(s, attrs);
s.onload = () => resolve(s);
s.onerror = () => { loaded.delete(src); reject(new Error('Failed to load ' + src)); };
document.head.append(s);
});
loaded.set(src, p);
return p;
}
// loadScript('https://cdn.example.com/chart.min.js').then(() => new Chart(...));Load a library only when a page needs it, and never load the same file twice.
function withTimeout(promise, ms, message = 'Timed out') {
let timer;
const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); });
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
const slow = new Promise((resolve) => setTimeout(() => resolve('late'), 200));
const result = withTimeout(slow, 20).catch((e) => e.message);Whichever settles first wins. Works for any promise, not only fetch.
class AppError extends Error {
constructor(message, options = {}) {
super(message, { cause: options.cause });
this.name = this.constructor.name;
this.code = options.code ?? 'APP_ERROR';
}
}
class ValidationError extends AppError {
constructor(field, message) { super(message, { code: 'VALIDATION' }); this.field = field; }
}
class NetworkError extends AppError {}
function check(email) {
if (!email.includes('@')) throw new ValidationError('email', 'Enter a valid e-mail');
}
let caught;
try { check('nope'); } catch (e) { caught = e; }Typed errors let callers react differently to different problems. cause keeps the original error.
async function downloadWithProgress(url, onProgress) {
const res = await fetch(url);
if (!res.ok) throw new Error('HTTP ' + res.status);
const total = Number(res.headers.get('content-length')) || 0;
const reader = res.body.getReader();
const chunks = [];
let received = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
received += value.length;
onProgress(total ? received / total : null);
}
return new Blob(chunks);
}Read the body in pieces so you can show a progress bar for big downloads.
const escapeHtml = (v) => String(v).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
function html(strings, ...values) {
return strings.reduce((out, str, i) => out + str + (i < values.length ? escapeHtml(values[i]) : ''), '');
}
const name = '<script>alert(1)</script>';
const markup = html`<p class="user">Hello ${name}</p>`;A tag function sees the fixed text and the values separately, so it can escape every value.
class Range {
constructor(from, to, step = 1) { Object.assign(this, { from, to, step }); }
*[Symbol.iterator]() {
for (let n = this.from; n <= this.to; n += this.step) yield n;
}
}
const evens = [...new Range(0, 10, 2)]; // [0, 2, 4, 6, 8, 10]
let total = 0;
for (const n of new Range(1, 4)) total += n; // 10Anything with [Symbol.iterator] works in for...of, spread and Array.from.
const secrets = new WeakMap();
class Account {
constructor(owner, pin) {
this.owner = owner;
secrets.set(this, { pin, tries: 0 });
}
unlock(pin) {
const s = secrets.get(this);
if (s.tries >= 3) return false;
if (s.pin === pin) { s.tries = 0; return true; }
s.tries++;
return false;
}
}
const acc = new Account('Ali', '1234');Data attached to an object that is cleaned up automatically when the object goes away.
const channel = new BroadcastChannel('app');
channel.onmessage = (e) => {
if (e.data.type === 'logout') {
location.href = '/login';
}
};
function logoutEverywhere() {
channel.postMessage({ type: 'logout' });
location.href = '/login';
}Log out in one tab and log out every tab, or keep a cart in sync.
const source = new EventSource('/events/notifications');
source.addEventListener('notification', (e) => {
const data = JSON.parse(e.data);
console.log('New:', data.title);
});
source.onerror = () => {
console.warn('Connection lost, the browser will retry');
};
// stop listening: source.close();
// PHP side (events.php):
// header('Content-Type: text/event-stream'); header('Cache-Control: no-cache');
// echo "event: notification\ndata: " . json_encode(['title' => 'Hello']) . "\n\n"; flush();Simpler than WebSockets when the server only needs to push. The browser reconnects automatically.
function connect(url, onMessage) {
let ws, retries = 0, closedByUser = false;
function open() {
ws = new WebSocket(url);
ws.onopen = () => { retries = 0; };
ws.onmessage = (e) => onMessage(JSON.parse(e.data));
ws.onclose = () => {
if (closedByUser) return;
const wait = Math.min(30000, 500 * 2 ** retries++) + Math.random() * 300;
setTimeout(open, wait);
};
}
open();
return {
send: (data) => ws.readyState === 1 && ws.send(JSON.stringify(data)),
close: () => { closedByUser = true; ws.close(); },
};
}Real-time messages with automatic retry using a growing delay.
function virtualList(container, items, rowHeight, renderRow) {
const spacer = document.createElement('div');
const view = document.createElement('div');
spacer.style.height = items.length * rowHeight + 'px';
spacer.style.position = 'relative';
view.style.position = 'absolute';
view.style.top = view.style.left = view.style.right = '0';
spacer.append(view);
container.replaceChildren(spacer);
function draw() {
const first = Math.max(0, Math.floor(container.scrollTop / rowHeight) - 3);
const count = Math.ceil(container.clientHeight / rowHeight) + 6;
view.style.transform = `translateY(${first * rowHeight}px)`;
view.replaceChildren(...items.slice(first, first + count).map((item, i) => renderRow(item, first + i)));
}
container.addEventListener('scroll', draw, { passive: true });
draw();
return draw;
}Render only the rows that are visible. The list stays fast with 100,000 items.
const curry = (fn) =>
function curried(...args) {
return args.length >= fn.length ? fn(...args) : (...more) => curried(...args, ...more);
};
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const compose = (...fns) => (x) => fns.reduceRight((v, f) => f(v), x);
const add = curry((a, b) => a + b);
const addTax = add(17); // partially applied
const slugify = pipe(
(s) => s.trim().toLowerCase(),
(s) => s.replace(/[^a-z0-9]+/g, '-'),
(s) => s.replace(/^-|-$/g, '')
);Small functions joined into bigger ones. pipe runs left to right.
function createStore(initial) {
const subscribers = new Set();
const state = new Proxy({ ...initial }, {
set(obj, key, value) {
const old = obj[key];
obj[key] = value;
if (old !== value) subscribers.forEach((fn) => fn(key, value, old));
return true;
},
});
return { state, subscribe: (fn) => (subscribers.add(fn), () => subscribers.delete(fn)) };
}
const { state, subscribe } = createStore({ count: 0, user: null });
const log = [];
subscribe((key, value) => log.push(key + '=' + value));
state.count++;
state.count++;
state.user = 'Ali';Change state like a normal object, and every subscriber is told. The idea behind many UI libraries.
function openDb(name = 'app', version = 1) {
return new Promise((resolve, reject) => {
const req = indexedDB.open(name, version);
req.onupgradeneeded = () => req.result.createObjectStore('notes', { keyPath: 'id', autoIncrement: true });
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
const run = (db, mode, fn) => new Promise((resolve, reject) => {
const tx = db.transaction('notes', mode);
const req = fn(tx.objectStore('notes'));
tx.oncomplete = () => resolve(req.result);
tx.onerror = () => reject(tx.error);
});
// const db = await openDb();
// await run(db, 'readwrite', (s) => s.add({ text: 'hello' }));
// const all = await run(db, 'readonly', (s) => s.getAll());Store lots of structured data in the browser. This wrapper turns the request callbacks into promises.
// sw.js (must be at the site root)
const CACHE = 'site-v1';
const FILES = ['/', '/assets/css/site.css', '/assets/js/site.js', '/offline.html'];
self.addEventListener('install', (e) => {
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(FILES)));
self.skipWaiting();
});
self.addEventListener('activate', (e) => {
e.waitUntil(caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))));
});
self.addEventListener('fetch', (e) => {
if (e.request.method !== 'GET') return;
e.respondWith(
caches.match(e.request).then((hit) => hit || fetch(e.request).catch(() => caches.match('/offline.html')))
);
});
// in the page: navigator.serviceWorker?.register('/sw.js');Serve files from the cache first, so the site opens even when the network is slow or gone.
const workerCode = `
self.onmessage = (e) => {
let sum = 0;
for (let i = 0; i < e.data; i++) sum += Math.sqrt(i);
self.postMessage(sum);
};
`;
function runInWorker(n) {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(new Blob([workerCode], { type: 'text/javascript' }));
const worker = new Worker(url);
worker.onmessage = (e) => { resolve(e.data); worker.terminate(); URL.revokeObjectURL(url); };
worker.onerror = (e) => { reject(e); worker.terminate(); };
worker.postMessage(n);
});
}
// runInWorker(50_000_000).then(console.log);A worker runs in another thread, so the page stays smooth. This one is created from a string, no extra file.
async function* items(baseUrl) {
let page = 1;
while (true) {
const res = await fetch(`${baseUrl}?page=${page}`);
const { data, hasMore } = await res.json();
yield* data; // hand out each item
if (!hasMore) return;
page++;
}
}
async function firstTen() {
const out = [];
for await (const item of items('/api/products')) {
out.push(item);
if (out.length === 10) break; // stops the requests too
}
return out;
}Hides the paging details. The loop just receives items, and stops asking when you break out.
function validated(target, rules) {
return new Proxy(target, {
set(obj, key, value) {
const rule = rules[key];
if (rule && !rule(value)) {
throw new TypeError(`Invalid value for ${String(key)}: ${value}`);
}
obj[key] = value;
return true;
},
get(obj, key) {
return key in obj ? obj[key] : undefined;
},
});
}
const user = validated({}, {
age: (v) => Number.isInteger(v) && v >= 0 && v < 130,
email: (v) => /^\S+@\S+\.\S+$/.test(v),
});
user.age = 30;
// user.age = -5; // TypeErrorA Proxy sits in front of an object and can check or react to every read and write.