[Javascript] debouncing, throttling 코드

남정호·2020년 5월 19일
0

javascript

목록 보기
1/1

코드

debouncing

function debounce(callback, delay) {
    let timeId;
    return function (...args) {
      clearTimeout(timeId);
      timeId = setTimeout(() => {
        callback(...args);
      }, delay);
    };
  }

throttling

  function throttle(callback, delay) {
    let timeId = false;
    return function (...args) {
      if (timeId) {
        return;
      }
      callback(...args);
      timeId = setTimeout(() => {
        timeId = false;
      }, delay);
    };
  }

예제

기본

  function foo(a) {
    console.log(a);
  }

  const bar = throttle(foo, 1000);

실전

<button class="btn">hi</button>
<script>
  function debounce(callback, delay) {
    let timeId;
    return function (...args) {
      clearTimeout(timeId);
      timeId = setTimeout(() => {
        callback(...args);
      }, delay);
    };
  }

  function throttle(callback, delay) {
    let timeId = false;
    return function (...args) {
      if (timeId) {
        return;
      }
      callback(...args);
      timeId = setTimeout(() => {
        timeId = false;
      }, delay);
    };
  }

  function foo(a) {
    console.log(a);
  }

  const bar = throttle(foo, 1000);
  document.querySelector(".btn").addEventListener("click", bar);
</script>

0개의 댓글