Debouncing & Throttling Kya Hote Hain?
Performance improve karne ke liye high-frequency events ko control karna sikhein.
1. Debouncing Kya Hota Hai?
Debouncing ek technique hai jo JavaScript me use hoti hai jab kisi function ko bar-bar aur unnecessary baar trigger hone se bachana hota hai. Yeh ensure karta hai ki function sirf tabhi execute ho jab user ka action thodi der ke liye ruk jaaye.
Matlab: Jab tak user event perform karta rahega, function call nahi hoga. Jaise hi kuch time tak action nahi hota, function ek baar execute hota hai.
Real Life Example:
Imagine karo tum search box mein type kar rahe ho: "hello". Debouncing ensure karta hai ki API call sirf tabhi ho jab aap typing band kar dein, na ki har 'h', 'e', 'l', 'l', 'o' ke liye.
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
const handleInput = debounce(function () {
console.log("API Call for search input...");
}, 300);
// input event listener
// document.getElementById("search").addEventListener("input", handleInput);
2. Throttling Kya Hota Hai?
Throttling ek technique hai jisme hum kisi function ko baar-baar call hone se rok kar, ek fix interval ke baad hi execute karne dete hain.
Throttling ensure karta hai ki function sirf har particular time gap ke baad hi chale, chahe event kitni bhi baar fire ho.
Real Life Example:
Socho tumhare paas ek scroll event hai. User continuously scroll karta hai. Throttling function ko har 200ms me sirf ek baar hi fire hone dega, chahe beech me 50 aur scroll events ho jaayein.
function throttle(func, interval) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= interval) {
lastCall = now;
func.apply(this, args);
}
};
}
const handleScroll = throttle(function () {
console.log("Scroll position updated");
}, 200);
// window.addEventListener("scroll", handleScroll);
Debounce vs. Throttling: Mukhya Antar
Feature | Debounce | Throttle |
---|---|---|
Trigger Timing | Event ke end me (delay ke baad) | Fixed interval mein |
Use Case | Jab user action stop kare (e.g., typing) | Jab constant activity ho (e.g., scrolling) |
Simple shabdon me: Debounce kehta hai, "Jab tak tum type kar rahe ho, main wait karunga. Jab tum rukoge, tab main kaam karunga." Throttle kehta hai, "Tum kitna bhi scroll karo, main har 200ms me ek baar hi kaam karunga."
Test Your Knowledge!
Kya aap Debouncing & Throttling ke baare mein seekh chuke hain? Chaliye dekhte hain!
Start Quiz