javascript
star
bookmark_border
Run a function only after the user stops typing or resizing.
function debounce(fn, wait = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
beginner
#performance #events #functions
javascript
star
bookmark_border
Abort a fetch that takes too long and handle HTTP errors.
async function getJSON(url, { timeout = 8000, ...options } = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const res = await fetch(url, { ...options, signal: controller.signal });
intermediate
#fetch #network #async
javascript
bookmark_border
Use the async clipboard API with a fallback for older browsers.
async function copyText(text) {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return true;
}
beginner
#clipboard #dom #ux
javascript
bookmark_border
structuredClone copies nested objects, Dates, Maps and Sets correctly.
const original = { user: { name: "Ada" }, created: new Date(), tags: new Set(["js"]) };
const copy = structuredClone(original);
copy.user.name = "Grace";
console.log(original.user.name); // Ada (unchanged)
beginner
#objects #data
javascript
bookmark_border
One listener on a parent handles clicks for current and future children.
document.body.innerHTML = `
<ul id="todo">
<li>Write tests <button data-action="done">Done</button></li>
<li>Deploy <button data-action="done">Done</button></li>
</ul>`;
intermediate
#dom #events #performance
javascript
bookmark_border
Let Intl format currency, numbers and dates instead of string hacks.
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const euros = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
const date = new Intl.DateTimeFormat("en-GB", { dateStyle: "medium" });
const ago = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
beginner
#intl #i18n #formatting
javascript
bookmark_border
Build an object of arrays with reduce (works everywhere, unlike Object.groupBy).
const orders = [
{ customer: "ada", total: 30 },
{ customer: "linus", total: 12 },
{ customer: "ada", total: 8 },
];
beginner
#arrays #data #objects
javascript
bookmark_border
Process many async jobs, but only N at a time.
async function mapLimit(items, limit, worker) {
const results = new Array(items.length);
let next = 0;
async function lane() {
while (next < items.length) {
advanced
#async #promises #performance