심플 디바운싱, 쓰로틀링

Taek·2021년 5월 9일
1

디바운싱 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);
     };
};

0개의 댓글