Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Debounce Function trong JavaScript

Debounce: giới hạn tần suất gọi hàm — chỉ thực thi sau khi **ngừng gọi** một khoảng thời gian.

Use case

  • Autocomplete search: chờ user ngừng gõ mới gọi API.
  • Resize/scroll handler: tránh gọi quá nhiều.
  • Button submit: tránh double-click.

Implementation

const debounce = (callback, delay) => {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => callback.apply(this, args), delay);
  };
};

Cách dùng

const debouncedSearch = debounce(query => {
  fetch('/api/search?q=' + query);
}, 300);

input.addEventListener('input', e => debouncedSearch(e.target.value));

Debounce vs Throttle

  • Debounce: đợi "yên tĩnh" delay ms mới chạy 1 lần.
  • Throttle: chạy tối đa 1 lần mỗi delay ms (cố định rate).

Thư viện: lodash.debounce, lodash.throttle.