8/17/19

Deboundce In The Javascript

Intro

I decided to wrote here all the things i know about the "debounce" termin
So: by saying "debounce" people mean - some functionality that blocks multiple event handlers from trigger until some specified time interval (like one second) passed.

Example: scroller, that fires lots of "scroll" events when user scrolling down, should respond only to last scroll event within second (specified time interval) and ignore all the rest of events within that second.

Implementation

The key thing for implementing debounce - is to know about "clearTimeout" method, which cancels the previously scheduled actions:


let timer = null;
const debounce = (fn, delay) => {
  // clean previously scheduled actions
  clearTimeout(timer);
  // scheduled  the last action
  timer = setTimeout(fn, delay);
};

document
  .querySelector("#myInput")
  .addEventListener("input", e =>
    debounce(_ => console.log(e.target.value), 1000)
  );
// you will see only last event appears after the delay

Or, if you want to store "timer" inside the function without polutting global scope:


var debounce = (fn, time, immediate) => {
  let timeout;
  return (...rest) => {
    const [args] = rest;

    const later = () => {
      if (!immediate) {
        timeout = null;
        fn(args);
      }
    };

    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, time);

    if (callNow) {
      fn(args);
    }
  };
};
…

document
  .getElementById("app")
  .addEventListener("input", debounce(handle, 1000));

function handle(e) {
  console.log(e.target.value);
}


No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...