📌 Debounce & Throttle
: 자주 사용되는 이벤트나 함수의 실행되는 빈도를 줄여서, 성능의 유리함을 가져오기 위한 개념
- 사용자의 의도와 무관한 요청을 줄이기 위한 기능 (input 입력 이벤트, API로 데이터를 가져오는 이벤트 등)
- 스크롤, 윈도우 리사이즈, 마우스 이동 등의 빈번한 이벤트에서 성능을 최적화하는 데 유용
- 이벤트가 과도하게 발생하는 것을 제한
✅ Debounce
: 입력 주기가 끝남과 동시에 이벤트를 호출한다.
- 같은 이벤트가 반복되게 발생하는 경우, 반복적으로 발생하던 이벤트가 일정 시간동안 다시 발생하지 않으면 콜백 함수를 실행
- 아무리 많은 이벤트가 발생해도 모두 무시하고 특정 시간 사이에 어떤 이벤트도 발생하지 않았을 때 딱 한번만 마지막 이벤트를 발생시킨다.
- 키워드 검색, 자동완성 기능, 사용자 창 크기 조정(윈도우 리사이즈)
function debounce(callback, limit = 100) {
let timeout
return function(...args) {
clearTimeout(timeout)
timeout = setTimeout(() => {
callback.apply(this, args)
}, limit)
}
}
설치
npm install debounce
사용
// debounce 불러오기
import debounce from 'debounce';
function resize() {
console.log('height', window.innerHeight);
console.log('width', window.innerWidth);
}
// debounce 사용하기
window.onresize = debounce(resize, 200);
예제
- 입력 이벤트 처리
// debounce 모듈 가져오기
const debounce = require('debounce');
// 입력 값이 변경될 때 호출되는 함수
function handleInputChange(event) {
console.log('Input value:', event.target.value);
}
// 300ms 지연된 debounce 함수
const debouncedHandleInputChange = debounce(handleInputChange, 300);
// HTML 문서에서 input 요소 찾기
const inputElement = document.getElementById('myInput');
// 'input' 이벤트가 발생할 때마다 debouncedHandleInputChange 함수를 호출
inputElement.addEventListener('input', debouncedHandleInputChange);
✅ Throttle
: 입력 주기를 방해하지 않고, 일정한 시간 간격으로 이벤트를 호출한다.
- 같은 이벤트가 반복되게 발생하는 경우, 일정 시간 간격으로 콜백 함수를 실행
- 스크롤 이벤트
- 스크롤 이벤트를 발생시키면, throttle을 사용한 함수는 매번 스크롤 이벤트가 발생할 때마다 실행되지 않고 정해진 간격으로만 실행된다.
function throttle(callback, limit = 100) {
let waiting = false
return function() {
if(!waiting) {
callback.apply(this, arguments)
waiting = true
setTimeout(() => {
waiting = false
}, limit)
}
}
}
설치
npm i lodash.throttle
사용
// lodash의 메서드 가져오기
const _ = require('lodash');
function handleScroll() {
console.log('스크롤 이벤트 발생!');
}
// throttle 사용
const throttledScroll = _.throttle(handleScroll, 1000);
window.addEventListener('scroll', throttledScroll);
예제
- 윈도우 리사이즈 이벤트 & 마우스 이동 이벤트 처리
// lodash의 throttle 함수 가져오기
const _ = require('lodash');
// 윈도우 리사이즈 이벤트 제어 함수
const throttledResize = _.throttle(function() {
console.log('윈도우 크기 변경 이벤트 발생!');
}, 500);
// 윈도우 리사이즈 이벤트에 throttledResize 함수를 추가
window.addEventListener('resize', throttledResize);
// 마우스 이동 이벤트 제어 함수
const throttledMouseMove = _.throttle(function(event) {
console.log(`마우스 위치: ${event.clientX}, ${event.clientY}`);
}, 200);
// 마우스 이동 이벤트에 throttledMouseMove 함수를 추가
window.addEventListener('mousemove', throttledMouseMove);