JS/[책] 모던 JS deep dive

41장. 타이머

web_seul 2023. 3. 8. 13:46
반응형

41.1 호출 스케줄링

일정시간이 경과된 후에 함수가 호출되도록 예약하는 방식

타이머 함수 : ECMAScript에 정의된 빌트인 함수가 아닌 호스트 객체(브라우저환경, Node.js 환경에서 전역 객체의 메서드로 제공) 

타이머 생성 : setTimeout, setInterval -> 타이머 만료시 콜백 함수 호출, 비동기 처리방식

타이머 제거 : clearTimeout, clearInterval

 

41.2 타이머 함수

setTimeout / clearTimeout

두번째 인수인 시간타이머가 만료되면 첫번째 인수인 콜백함수가 호출됨, setTimeout 함수가 생성한 고유타이머 id를 clearTimeout 함수의 인수로 전달하여 타이머 취소

const timeoutId = setTimeout(func|code[, delay, param1, param2, ...]);

 

setInterval / clearInterval

두번째 인수로 전달받은 시간이 만료될 때마다 반복하는 첫번째 인수인 콜백함수가 호출됨, setInterval 함수가 생성한 고유타이머 id를 clearInterval 함수의 인자로 전달하여 타이머 취소

const timeoutId = setInterval(func|code[, delay, param1, param2, ...]);

 

41.3 디바운스와 스로틀

scroll, resize, input, mousemove와 같이 연속적으로 발생하는 이벤트를 그룹화하여 과도한 이벤트 핸들러의 호출 방지

 

디바운스(debounce) : 짧은 시간 간격으로 발생하는 이벤트를 그룹화하여 마지막 한번만 이벤트 핸들러가 호출되도록 함, Underscore의 debounce 함수, Lodash의 debounce 함수 사용 권장

* https://underscorejs.org/#debounce  * https://lodash.com/docs/4.17.15#debounce

const $input = document.querySelector('input');
const $msg = document.querySelector('.msg');

const debounce = (callback, delay) => {
  let timerId;	//debounce 함수는 timeId를 기억하는 클로저를 반환
  return (...args) => {
  
    //delay가 경과하기 이전에 이벤트가 발생하면 이전 타이머를 취소하고 새로운 타이머를 재설정
    //따라서 delay보다 짧은 간격으로 이벤트 발생시 callback 호출 없음
    if(timerId) clearTimeout(timerId);
    timerId = setTimeout(callback, delay, ...args);
  }
}

//debounce 함수가 반환하는 클로저가 이벤트 핸들러로 등록됨
//300ms 보다 짧은 간격으로 이벤트가 발생하면 debounce 함수의 콜백 함수는 호출되지 않다가
//300ms 동안 이벤트가 발생하지 않으면 한 번만 호출됨
$input.oninput = debounce(e => {
  $msg.textContent = e.target.value;
}, 300);

 

스로틀(throttle) : 짧은 시간 간격으로 연속적으로 발생하는 이벤트를 그룹화하여 한 번만 호출되도록 함, Underscore의 throttle 함수, Lodash의 throttle 함수 사용 권장

* https://underscorejs.org/#throttle  * https://lodash.com/docs/4.17.15#throttle

 

Underscore.js

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being produc

underscorejs.org

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));

 

반응형

'JS > [책] 모던 JS deep dive' 카테고리의 다른 글

39장. DOM  (0) 2023.02.22
36장. 디스트럭처링 할당  (0) 2023.02.21
35장. 스프레드 문법 (임시저장)  (0) 2023.02.21
26장. ES6 함수의 추가 기능  (0) 2023.01.18
22장. this  (0) 2023.01.11