Throttle and Debounce using setTimeout and setInterval

In this post I show how to throttle a function using setInterval and how to debounce a function using setTimeout. Throttling and debouncing are two similar technique to reduce the workload on the server or client by limiting the rate at which a function is invoked for example during scrolling a page or entering a value in a text field, etc. You can see a visual representation of each technique here:

https://web.archive.org/web/20180324022838/http://demo.nimius.net/debounce_throttle/

Below examples show value entered by user inside an input field under the field using debounce and throttle techniques:

Debounce via setTimeout

const div = document.querySelector('div');
document.querySelector('input').addEventListener('input', (e) => {
  myFunction(e.target.value);
});

let timer: ReturnType<typeof setTimeout> | undefined = undefined;

const myFunction = (txt) => {
  clearTimeout(timer);
  timer = setTimeout(() => {
    div.innerHTML = txt;
  }, 500);
}

Codepen

Throttle via setInterval

const div = document.querySelector('div');
let inputValue;
let changed = false;
document.querySelector('input').addEventListener('input', (e) => {
  changed = true;
  inputValue = e.target.value;
});

const myInterval = setInterval(() => {
  if (changed) {
    changed = false;
    div.innerHTML = inputValue;
  }
}, 500);

Codepen