타이머 41

호출 스케줄링

setImteout 함수의 콜백 함수는 타이머가 만료되면 단 한 번 호출되고,
setInterval 함수의 콜백 함수는 타이머가 만료될 때마다 반복 호출된다.

자바스크립트 엔진은 단 하나의 실행 컨텍스트 스택을 갖기 때문에 두 가지 이상의 태스크를 동시에 실행할 수 없다.
즉, 자바스크립트 엔진은 싱글 스레드로 동작한다.
이런 이유로 타이머 함수 setTimeout과 setInterval은 비동기 처리 방식으로 동작한다.

타이머 함수

setTimeout / clearTimeout

const timeoutId = setTimeout(func|code[, delay, param1, param2, ...]);
const timerId = setTimeout(name => console.log(`Hi : ${name}`), 1000, 'lee');
clearTimeout(timerId);

setInterval / clearInterval

const timerId = setInterval(func|code[, delay, param1, param2, ...]);
let count = 1;
const timerId = setInterval(() => {
    console.log(count);
    if(count++ === 5) clearInterval(timerId);
}, 1000);

디바운스와 스로틀

scroll, resize, input, mousemove, mouseover 같은 이벤트는 짧은 시간 간격으로 연속해서 발생한다.
이러한 이벤트에 바인딩한 이벤트 핸들러는 과도하게 호출되어 성능에 문제를 일으킬 수 있다.
디바운스와 스로틀은 짧은 시간 간격으로 연속해서 발생하는 이벤트를 그룹화해서 과도한 이벤트 핸들러의 호출을 방지하는 프로그래밍 기법이다.

<!DOCTYPE html>
<html>
<body>
    <button>click me</button>
    <pre>일반 클릭 이벤트 카운터 <span class="normal-msg">0</span> </pre>
    <pre>debounce 클릭 이벤트 카운터 <span class="debounce-msg">0</span> </pre>
    <pre>throttle 클릭 이벤트 카운터 <span class="throttle-msg">0</span> </pre>
    <script>
        const $button = document.querySelector('button');
        const $normalMsg = document.querySelector('.normal-msg');
        const $debounceMsg = document.querySelector('.debounce-msg');
        const $throttleMsg = document.querySelector('.throttle-msg');

        const debounce = (callback, delay) => {
          let timerId;
          return event => {
            if(timerId) clearTimeout(timerId);
            timerId = setTimeout(callback, delay, event);
          };
        }

        const throttle = (callback, delay) => {
          let timerId;
          return event => {
            if(timerId) return;
            timerId = setTimeout(() => {
              callback(event);
              timerId = null;
            }, delay, event);
          }; 
        }
        
        $button.addEventListener('click', () => {
          $normalMsg.textContent = +$normalMsg.textContent + 1;
        });

        $button.addEventListener('click', () => {
          $debounceMsg.textContent = +$debounceMsg.textContent + 1;
        });

        $button.addEventListener('click', () => {
          $throttleMsg.textContent = +$throttleMsg.textContent + 1;
        });
    </script>
</body>
</html>

디바운스

디바운스는 짧은 시간 간격으로 발생하는 이벤트를 그룹화해서 마지막에 한 번만 이벤트 핸들러가 호출되도록 한다.
디바운스는 resize 이벤트 처리나 input 요소에 입력된 값으로 ajax 요청하는 입력 필드 자동완성 UI 구현, 버튼 중복 클릭 방지 처리 등에 유용하게 사용된다.

<!DOCTYPE html>
<html>
<body>
    <input type="text">
    <div class="msg"></div>
    <script>
        const $input = document.querySelector('input');
        const $msg = document.querySelector('.msg');

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

위 예제의 debounce 함수는 이해를 위해 간략하게 구현하여 완전하지 않다.
실무에서는 Underscore의 debounce 함수나 Lodash의 debounce 함수를 사용하는 것을 권장한다.

스로틀

스로클은 짧은 시간 간격으로 연속해서 발생하는 이벤트를 그룹화해서 일정 시간 단위로 이벤트 핸들러가 호출되도록 호출 주기를 만든다.

<!DOCTYPE html>
<html>
<head>
    <style>
        .container{width:300px;height:300px;background-color:rebeccapurple;overflow:scroll;}
        .content{width:300px;height:1000vh;}
    </style>
</head>
<body>
    <div class="container">
        <div class="content"></div>
    </div>
    <div>
        일반 이벤트 핸들러가 scroll 이벤트를 처리한 횟수: <span class="normal-count">0</span>
    </div>
    <div>
        스로틀 이벤트 핸들러가 scroll 이벤트를 처리한 횟수: <span class="throttle-count">0</span>
    </div>
    <script>
        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 event => {
            // delay가 경과하기 이전에 이벤트가 발생하면 아무것도 하지 않다가
            // delay가 경과했을 때 이벤트가 발생하면 새로운 타이머를 재설정한다.
            // 따라서 delay 간격으로 callback이 호출된다.
            if(timerId) return;
            timerId = setTimeout(() => {
              callback(event);
              timerId = null;
            }, delay, event);
          }; 
        };
        
        let normalCount = 0;
        $container.addEventListener('scroll', () => {
            $normalCount.textContent = ++normalCount;
        });

        let throttleCount = 0;
        // throttle 함수가 반환하는 클로저가 이벤트 핸들러로 등록된다.
        $container.addEventListener('scroll', throttle(() => {
            $throttleCount.textContent = ++throttleCount;
        }, 100));
    </script>
</body>
</html>

스로틀은 scroll 이벤트 처리나 무한 스크롤 UI 구현 등에 유용하게 사용된다.
위 예제의 throttle 함수는 이해를 위해 간략하게 구현하여 완전하지 않다.
실무에서는 Underscore의 throttle 함수나 Lodash의 throttle 함수를 사용하는 것을 권장한다.