디바운싱 1
const debounce = function (callback, waitTime) {
let timerId = null;
return (e) => {
clearTimeout(timerId);
timerId = setTimeout(callback.bind(this, e), waitTime);
};
};
const eventHandler = function() { ... };
el.addEventListener('mousemove', debounce.call(this, eventHandler, 500));
디바운싱 2
const debounce = function (callback, waitTime) {
let firstCallback = null;
let timerId = null;
return (e) => {
if (!firstCallback) firstCallback = callback;
clearTimeout(timerId);
timerId = setTimeout(firstCallback.bind(this, e), waitTime);
};
};
쓰로틀링
const throttle = function (callback, waitTime) {
let timerId = null;
return (e) => {
if (timerId) return;
timerId = setTimeout(() => {
callback.call(this, e);
timerId = null;
}, waitTime);
};
};