setTimeout
Belirli süre sonra bir kez çalışır:
const id = setTimeout(() => {
console.log("1 saniye geçti");
}, 1000);
// Henüz çalışmadıysa iptal et
clearTimeout(id);İlk argüman fonksiyon, ikincisi ms cinsinden gecikme.
setInterval
Belirtilen aralıkla sürekli çalışır:
const id = setInterval(() => {
console.log("her saniye");
}, 1000);
// Durdur
clearInterval(id);setInterval, callback'in çalışma süresini umursamaz. Eğer callback
500ms sürer ve interval 200ms ise işlem birikir. Bu yüzden çoğu durumda
setTimeout rekürsif daha güvenli:
function loop() {
yap();
setTimeout(loop, 200);
}
loop();requestAnimationFrame
UI animasyonu için. Bir sonraki repaint'ten önce çalışır (genelde 60fps):
function animate() {
// konum güncelle, render et
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);setInterval'a göre tarayıcıya saygılıdır — sekme arka plandayken çalışmaz.
queueMicrotask
Mevcut işlem bittikten sonra ama setTimeout'tan önce çalışır:
queueMicrotask(() => {
console.log("microtask");
});Promise.resolve().then(...) ile aynı timing.
Debounce
Hızlı tekrar eden olayları azalt: kullanıcı durduktan sonra bir kez çalış.
function debounce(fn, ms = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
// Kullanım: arama input'u
const onSearch = debounce((q) => {
fetch(`/api/search?q=${q}`);
}, 400);
input.addEventListener("input", (e) => onSearch(e.target.value));Kullanıcı yazmayı bıraktıktan 400ms sonra istek atılır. Ara tıklamalar iptal olur.
Throttle
Olayı belirli aralıklarla kısıtla — ne kadar sık tetiklense de en fazla şu sıklıkla çalışsın.
function throttle(fn, ms = 300) {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= ms) {
lastCall = now;
fn(...args);
}
};
}
// Kullanım: scroll
const onScroll = throttle(() => {
console.log("scroll", window.scrollY);
}, 100);
window.addEventListener("scroll", onScroll);Debounce mı throttle mı?
| Senaryo | Tercih |
|---|---|
| Arama input'u | debounce |
| Form validasyon | debounce |
| Scroll position takibi | throttle |
| Window resize | debounce (son boyut) veya throttle |
| Buton spam | debounce |
| Auto-save | debounce |
| Drag/move | throttle |
Production önerisi
Kendin yazmadan, lodash-es'ten al:
import { debounce, throttle } from "lodash-es";
const search = debounce(fn, 300, { leading: false, trailing: true });Edge case'leri (cancel, flush, leading/trailing) hazır gelir.