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));
'공부공부 > JS 딥다이브' 카테고리의 다른 글
[js 딥다이브] 43장 Ajax (0) | 2024.02.18 |
---|---|
[js 딥다이브] 42장 비동기 프로그래밍 (0) | 2024.02.18 |
[js 딥다이브] 40장 이벤트 (1) | 2024.02.18 |
[js 딥다이브] 39장 DOM (0) | 2024.02.18 |
[js 딥다이브] 38장 브라우저의 렌더링 과정 (0) | 2024.02.18 |