Skip to content

Instantly share code, notes, and snippets.

@cmbaughman
Created October 21, 2025 18:29
Show Gist options
  • Select an option

  • Save cmbaughman/070bc530d22110a05cc240f89026157d to your computer and use it in GitHub Desktop.

Select an option

Save cmbaughman/070bc530d22110a05cc240f89026157d to your computer and use it in GitHub Desktop.
Useful Javascript Tips
/////////////////////////////////////////////////////////
// Debounce: wait until the user stops typing
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
// Example: Search input
const handleSearch = debounce((query) => {
console.log("Fetching results for:", query);
}, 300);
document.getElementById("search").addEventListener("input", e => {
handleSearch(e.target.value);
});
///////////////////////////////
// Smoooth animations
function animateBox(timestamp) {
box.style.transform = `translateX(${Math.sin(timestamp / 200) * 100}px)`;
requestAnimationFrame(animateBox);
}
const box = document.getElementById("box");
requestAnimationFrame(animateBox);
////////////////////////////////////
// Lazy loaded dynamic imports
document.getElementById("open-chart").addEventListener("click", async () => {
const { renderChart } = await import("./chart.js");
renderChart();
});
/////////////////////////////////////
// Minimize Reflows and Repaints
// DOM updates are expensive. Frequent changes cause the browser to recalculate styles and re-render.
// Use batching:
// Bad ❌
for (let i = 0; i < 1000; i++) {
document.body.appendChild(document.createElement("div"));
}
// Good ✅
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
fragment.appendChild(document.createElement("div"));
}
document.body.appendChild(fragment); // Only one reflow
////////////////////////////////////////
// Offload work to a Web Worker
// worker.js
self.onmessage = function (e) {
const result = heavyComputation(e.data);
postMessage(result);
};
// main.js
const worker = new Worker("worker.js");
worker.postMessage(1000000);
worker.onmessage = (e) => console.log("Result:", e.data);
/////////////////////////////////////////////////////
// Cache Expensive Results with Memoization
// Avoid recalculating the same result over and over.
function memoize(fn) {
const cache = {};
return function (arg) {
if (cache[arg]) return cache[arg];
return (cache[arg] = fn(arg));
};
}
const slowFib = (n) => (n <= 1 ? n : slowFib(n - 1) + slowFib(n - 2));
const fastFib = memoize(slowFib);
console.log(fastFib(40)); // much faster after first run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment