debouncing, throttling

steyu·2023년 3월 6일
0
let timer;

// debounce: 마지막 함수만 호출
document.querySelector("#input").addEventListener("input", function (e) {
  if (timer) {
    clearTimeout(timer);
  }

  timer = setTimeout(() => {
    console.log(e.target.value);
  }, 2000);
});

// throttling: 마지막 함수이후 정해진 시간이 지나기전 호출방지
document.querySelector("#input").addEventListener("input", function (e) {
  if (!timer) {
    timer = setTimeout(() => {
      timer = null;
      console.log(e.target.value);
    }, 2000);
  }
});

0개의 댓글