디바운스(Debounce), 스로틀(Throttle), 레이아웃 스레싱(Layout Thrashing)

|

1. 디바운스(Debounce)

- 이벤트를 그룹화하여 특정시간이 지난 후 하나의 이벤트만 발생하도록 하는 것

 

2. 스로틀(Throttle)

- 이벤트를 일정한 주기마다 발생하도록 하는 것

function throttle(func, wait, debounce) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var throttler = function () {
            timeout = null;
            func.apply(context, args);
        };
        if (debounce) clearTimeout(timeout);
        if (debounce || !timeout) timeout = setTimeout(throttler, wait);
    };
}

 

3. 레이아웃 스레싱(Layout Thrashing)

- 강제 동기 레이아웃

- 발생 시, reflow 계산을 위해 메인 쓰레드가 블락킹 되므로 성능에 치명적인 원인이 됨.(데스크톱에서는 심하지만, 모바일에서는 심각한 성능 저하가 존재)

- 해결책 : requestAnimationFrame을 사용하여 DOM을 읽는 로직은 현재 프레임에서 실행하고, DOM을 수정하기 위한 로직은 requestAnimationFrame와 함께 사용해 다음 프레임에서 함께 실행하도록 예약

/**
 * @param fn {Function}
 * @param [throttle] {Boolean|undefined}
 * @return {Function}
 *
 * @example
 * // generate rAFed function
 * jQuery.fn.addClassRaf = bindRaf(jQuery.fn.addClass);
 *
 * //use rAFed function
 * $('div').addClassRaf('is-stuck');
 */
function bindRaf(fn, throttle){
  var isRunning, that, args;
  var run = function(){
    isRunning = false;
    fn.apply(that, args);
  };

  return function(){
    that = this;
    args = arguments;

    if(isRunning && throttle){
      return;
    }

    isRunning = true;
    requestAnimationFrame(run);
  };
}

 

'JavaScript' 카테고리의 다른 글

reduce()  (0) 2023.01.10
Reflow  (0) 2023.01.02
x,y 두 좌표의 직선거리 구하기  (0) 2022.12.16
dotenv, express, axios  (0) 2021.12.31
var, let, const의 차이점은?  (0) 2021.11.30
And