디바운싱
- 연속적으로 호출되는 함수들 중에서 처음 or 마지막에 호출되는 함수만 실행하는 방식(함수는 한 번만 실행)
- 주로 이벤트 핸들러에 적용
// #1 타이머 예제
let timer;
document.querySelector('#input').addEventListener('input', function(e) {
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
// 실행할 코드 내용
}, 200);
});
// #2 텍스트 입력 예제
function debounce(func, delay) {
let timeoutId;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
const inputField = document.getElementById('inputField');
inputField.addEventListener('input', debounce(function() {
// 실행할 코드 내용
}, 300));
쓰로틀링
- 마지막 함수가 호출된 후 일정 시간이 지나기 전에 다시 호출되지 않도록 하는 방식
- 일정 시간 간격마다 함수를 실행하도록 제어
// #1 타이머 예제
let timer;
document.querySelector('.body').addEventListener('scroll', function (e) {
if (! timer) {
timer = setTimeout(function() {
timer = null;
// 실행할 코드 내용
}, 200);
}
});
// #2 마우스 이동
function throttle(func, delay) {
let throttleTimeout;
return function() {
const context = this;
const args = arguments;
if (!throttleTimeout) {
throttleTimeout = setTimeout(() => {
func.apply(context, args);
throttleTimeout = null;
}, delay);
}
};
}
window.addEventListener('mousemove', throttle(function(event) {
// 실행할 코드 내용
}, 300));
'Frontend > JavaScript' 카테고리의 다른 글
$(document).ready() 와 window.onload 의 차이점 (0) | 2024.07.01 |
---|---|
자바스크립트의 동작 원리 (0) | 2024.02.03 |
window 객체의 opener 사용하기 (0) | 2023.10.15 |
자바스크립트 null, undefined, NaN의 차이 (0) | 2023.10.08 |
크롬 브라우저에서 자바스크립트 디버깅 하는 법 (0) | 2023.08.27 |