Throttle와 Debounce는 DOM 이벤트를 기반으로 실행하는 자바스크립트의 이벤트 콜백을 제어 및 제한하는 방법을 말한다.
- Throttle
함수가 밀리초마다 한번 이상 실행되지 않도록 제한하는 것을 말한다.
Throttle는 적어도 x 밀리초마다 정기적으로 함수 실행을 보장한다.
// Very simple example.
// Probably you would want to use a 
// full-featured plugin like
// https://github.com/infinite-scroll/infinite-scroll/blob/master/jquery.infinitescroll.js
$(document).ready(function(){
  
  // Check every 300ms the scroll position
  $(document).on('scroll', _.throttle(function(){
    check_if_needs_more_content();
  }, 300));
  function check_if_needs_more_content() {     
    pixelsFromWindowBottomToBottom = 0 + $(document).height() - $(window).scrollTop() -$(window).height();
    
  // console.log($(document).height());
  // console.log($(window).scrollTop());
  // console.log($(window).height());
  //console.log(pixelsFromWindowBottomToBottom);
    
    
    if (pixelsFromWindowBottomToBottom < 200){
      // Here it would go an ajax request
      $('body').append($('.item').clone()); 
      
    }
  }
});- Debounce
여러개의 순차적 호출을 단일 호출로 그룹화하는 것을 말한다.

// Based on http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
$(document).ready(function(){
  
  var $win = $(window);
  var $left_panel = $('.left-panel');
  var $right_panel = $('.right-panel');
  
  function display_info($div) {
    $div.append($win.width() + ' x ' + $win.height() +  '<br>');
  }
                
  $(window).on('resize', function(){
    display_info($left_panel);
  });
  
  $(window).on('resize', _.debounce(function() {
    display_info($right_panel);
  }, 400));
});
# REFRENCE
https://css-tricks.com/debouncing-throttling-explained-examples/
https://lodash.com/docs#throttle
http://underscorejs.org/#throttle
반응형
    
    
    
  '개발 > Web' 카테고리의 다른 글
| PSR-0, PSR-1, PSR-2 (PHP Standards Recommendations) (0) | 2020.09.07 | 
|---|---|
| PHP 7 엄격한 타이핑 (strict mode) (0) | 2020.09.07 | 
| CSS Pro-Processor(전처리기) SASS, SCSS, LESS (0) | 2020.08.23 | 
| 주요 렌더링 경로(Critical Rendering Path) (0) | 2020.08.22 | 
| Javascript 동기식/비동기식 처리 (0) | 2020.08.20 | 
 
									
								