اگه مستقیم به scroll، resize یا input تابع سنگین وصل کردی، داری CPU کاربر رو میسوزونی! 🔥
اینا میان وسط:
🔹 Debounce → صبر کن کاربر دست از کار بکشه، بعد اجرا کن
🔹 Throttle → هر X میلیثانیه یه بار اجرا کن، نه بیشتر
🧩Debounce
function debounce(fn, delay = 500) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
// جستجوی زنده
input.addEventListener("input", debounce(e => {
fetch(`/search?q=${e.target.value}`);
}, 600));تا کاربر تایپ نکنه، درخواست نمیره ✅
یعنی نه سرور درگیر میشه، نه UI لگ میزنه.
🧩 Throttle
function throttle(fn, limit = 200) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= limit) {
last = now;
fn(...args);
}
};
}
// اسکرول
window.addEventListener("scroll", throttle(() => {
console.log(window.scrollY);
}, 300));هر ۳۰۰ms یه بار، نه بیشتر ✅
یعنی پرفورمنس عالی
🎯 کجا استفاده کنیم؟
جستجوی زنده Debounce
اعتبارسنجی فرم Debounce
رویداد scroll Throttle
رویداد resize Throttle
@perfino_com