BKJang / dev-tips

📚 This repository is a collection of development tips and troubleshooting I have experienced during development.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Throttling & Debouncing Simple Util

BKJang opened this issue · comments

❗️ Throttling

function throttled(delay, fn) {
  let lastCall = 0;
  return function (...args) {
    const now = (new Date).getTime();
    if (now - lastCall < delay) {
      return;
    }
    lastCall = now;
    return fn(...args);
  }
}

❗️ Debouncing

function debounced(delay, fn) {
  let timerId;
  return function (...args) {
    if (timerId) {
      clearTimeout(timerId);
    }
    timerId = setTimeout(() => {
      fn(...args);
      timerId = null;
    }, delay);
  }
}

🙏 Reference