본문 바로가기
개발공부 일지/면접

자바스크립트)Throttling(쓰로틀링) vs Debounce(디바운스)

by Box Cat 2023. 10. 3.
728x90
반응형
 

쓰로틀링:

한번 로직이 실행 되고 나면 정해진 시간 동안 해당 로직의 실행을 막는 방식. 

function throttle(func, delay) {
    let lastCallTime = 0;
   
    return function(...args) {
      const now = Date.now();
     
      if (now - lastCallTime >= delay) {
        func(...args);
        lastCallTime = now;
      }
    };
  }
 
  // 예시 함수
  function doSomething() {
    console.log("실행됨!");
  }
 
  // 쓰로틀링된 함수 생성
  const throttledFunction = throttle(doSomething, 1000); // 1초에 한 번만 실행되도록 제어
 
  // 이벤트 핸들러 등에서 호출
  window.addEventListener("scroll", throttledFunction);//window는 브라우저 환경에서만 실행가능
 

 

 

디바운스:

이벤트 발생이 종료되고 정해진 시간이 지날 동안 이벤트가 다시 발생하지 않으면 로직을 실행하는 방식.

정해진 시간이 지나기 전에 이벤트가 다시 발생하면 다시 처음부터 그 시간을 기다린다.

 
const EventEmitter = require('events');

class ThrottleEmitter extends EventEmitter {}

const throttleEmitter = new ThrottleEmitter();

function throttle(func, delay) {
  let lastCallTime = 0;

  return function (...args) {
    const now = Date.now();

    if (now - lastCallTime >= delay) {
      func(...args);
      lastCallTime = now;
    }
  };
}

// 예시 함수
function doSomething() {
  console.log("실행됨!");
}

// 쓰로틀링된 함수 생성
const throttledFunction = throttle(doSomething, 1000); // 1초에 한 번만 실행되도록 제어

// 이벤트 핸들러 등록
throttleEmitter.on("scroll", () => {
  throttledFunction();
});

// 이벤트 시뮬레이션 (예시로 scroll 이벤트를 발생시킵니다.)
setInterval(() => {
  throttleEmitter.emit("scroll");
}, 500); // 0.5초 간격으로 이벤트 발생
 
728x90
반응형

'개발공부 일지 > 면접' 카테고리의 다른 글

MVC vs MVP vs MVVM  (0) 2023.10.04
전략 패턴(Strategy Pattern)  (0) 2023.10.03
파사드 패턴(Facade Pattern)  (0) 2023.10.03
팩토리 패턴(Factory Pattern)  (0) 2023.10.03
추상 팩토리 패턴 ( Abstract Factory Pattern )  (0) 2023.10.03

댓글