Day 36

Performance Optimization

12 min
JavaScript 100 Days

Fast website user experience ko better banata hai aur SEO mein bhi help karta hai. JavaScript performance optimize karna bahut zaroori hai real-world apps mein.

Debounce & Throttle

Frequent events ko control karo — search input, scroll, resize.

debounce-throttle.js
javascript
// Debounce — last call ke baad delay
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

// Throttle — har X ms mein ek baar
function throttle(fn, ms) {
  let lastTime = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastTime >= ms) {
      lastTime = now;
      fn(...args);
    }
  };
}

// Search bar — debounce karo
const searchInput = document.getElementById("search");
searchInput.addEventListener("input", debounce(e => {
  console.log("Searching:", e.target.value);
}, 300));

// Scroll — throttle karo
window.addEventListener("scroll", throttle(() => {
  console.log("Scroll position:", window.scrollY);
}, 100));

🎯 Practice Challenge

Search bar banao with debounce (300ms). Scroll position tracker banao with throttle (100ms).