코드
debouncing
function debounce(callback, delay) {
let timeId;
return function (...args) {
clearTimeout(timeId);
timeId = setTimeout(() => {
callback(...args);
}, delay);
};
}
throttling
function throttle(callback, delay) {
let timeId = false;
return function (...args) {
if (timeId) {
return;
}
callback(...args);
timeId = setTimeout(() => {
timeId = false;
}, delay);
};
}
예제
기본
function foo(a) {
console.log(a);
}
const bar = throttle(foo, 1000);
실전
<button class="btn">hi</button>
<script>
function debounce(callback, delay) {
let timeId;
return function (...args) {
clearTimeout(timeId);
timeId = setTimeout(() => {
callback(...args);
}, delay);
};
}
function throttle(callback, delay) {
let timeId = false;
return function (...args) {
if (timeId) {
return;
}
callback(...args);
timeId = setTimeout(() => {
timeId = false;
}, delay);
};
}
function foo(a) {
console.log(a);
}
const bar = throttle(foo, 1000);
document.querySelector(".btn").addEventListener("click", bar);
</script>