</>
⌕
Mid #debounce#throttle#performance#closure

debounce và throttle khác nhau thế nào? Viết code mỗi loại

⚡ Trả lời nhanh

Debounce hoãn gọi hàm cho đến khi ngừng kích hoạt đủ N ms (phù hợp ô tìm kiếm, resize xong). Throttle đảm bảo hàm chạy tối đa một lần mỗi N ms (phù hợp scroll, mousemove). Cả hai đều dựa vào closure giữ timer hoặc timestamp.

Khác biệt

debouncethrottle
Hành vichỉ chạy sau khi im lặng N mschạy đều đặn, tối đa 1 lần/N ms
Use casesearch-as-you-type, autosavescroll, resize, drag
Reset timermỗi lần gọikhông

Code

function debounce(fn, ms) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), ms);
  };
}

function throttle(fn, ms) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= ms) {
      last = now;
      fn.apply(this, args);
    }
  };
}

Bản trên là throttle kiểu leading. Bản đầy đủ thêm trailing call (gọi lần cuối sau khoảng nghỉ) và cancel(). Với animation, requestAnimationFrame thường thay throttle cho scroll/mousemove.

🃏 Ôn bằng flashcard