공부공부/JS 딥다이브

[js 딥다이브] 41장 타이머

고생쨩 2024. 2. 18. 10:02
728x90

타이머

타이머 함수

setTimeout, clearTimeout

setInterval, clearInterval

디바운스와 스로틀

디바운스

const $input = document.querySelector('input');
const $msg = document.querySelector('.msg');
const debounce = (callback, delay) => {
let timerId;
// debounce 함수는 timerId를 기억하는 클로저를 반환한다.
  return (...args) => {
  // delay가 경과하기 이전에 이벤트가 발생하면 이전 타이머를 취소하고 새로운 타이머를 재설정한다.
  // 따라서 delay보다 짧은 간격으로 이벤트가 발생하면 callback은 호출되지 않는다.
  if (timerId) clearTimeout(timerId);
    timerId = setTimeout(callback, delay, ...args);
  };
};
// debounce 함수가 반환하는 클로저가 이벤트 핸들러로 등록된다.
// 300ms보다 짧은 간격으로 input 이벤트가 발생하면 debounce 함수의 콜백 함수는
// 호출되지 않다가 300ms 동안 input 이벤트가 더 이상 발생하지 않으면 한 번만 호출된다.
$input.oninput = debounce(e => {
$msg.textContent = e.target.value;
}, 300)

스로틀

const $container = document.querySelector('.container');
const $normalCount = document.querySelector('.normal-count');
const $throttleCount = document.querySelector('.throttle-count');
const throttle = (callback, delay) => {
  let timerId;
  // throttle 함수는 timerId를 기억하는 클로저를 반환한다.
  return (...args) => {
    // delay가 경과하기 이전에 이벤트가 발생하면 아무것도 하지 않다가
    // delay가 경과했을 때 이벤트가 발생하면 새로운 타이머를 재설정한다.
    // 따라서 delay 간격으로 callback이 호출된다.
    if (timerId) return;
      timerId = setTimeout(() => {
      callback(...args);
      timerId = null;
    }, delay);
  };
};
let normalCount = 0;
$container.addEventListener('scroll', () => {
  $normalCount.textContent = ++normalCount;
});
let throttleCount = 0;
// throttle 함수가 반환하는 클로저가 이벤트 핸들러로 등록된다.
$container.addEventListener('scroll', throttle(() => {
  $throttleCount.textContent = ++throttleCount;
}, 100));  

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.