Files
30-seconds-of-code/snippets/js/s/debounce-function.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

1.2 KiB

title, type, language, tags, cover, excerpt, dateModified
title type language tags cover excerpt dateModified
Debounce function snippet javascript
function
solitude-beach Creates a debounced function that waits `ms` milliseconds before invoking the provided function again. 2021-10-13T19:29:39+02:00

Creates a debounced function that delays invoking the provided function until at least ms milliseconds have elapsed since its last invocation.

  • Each time the debounced function is invoked, clear the current pending timeout with clearTimeout(). Use setTimeout() to create a new timeout that delays invoking the function until at least ms milliseconds have elapsed.
  • Use Function.prototype.apply() to apply the this context to the function and provide the necessary arguments.
  • Omit the second argument, ms, to set the timeout at a default of 0 ms.
const debounce = (fn, ms = 0) => {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), ms);
  };
};
window.addEventListener(
  'resize',
  debounce(() => {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }, 250)
); // Will log the window dimensions at most every 250ms