フロントエンドスロットルと振れ防止


1.ブレ止めの理解(debounce)
search検索レノボでは,ユーザが値を入力し続ける間に,ジッタ防止で要求リソースを節約する.
Windowsがresizeをトリガすると、ブラウザウィンドウのサイズを絶えず調整すると、このイベントが絶えずトリガされ、振れ止めで一度だけトリガされます
スロットル
マウスをクリックしてトリガーし、mousedown(単位時間に1回のみトリガー)
スクロールイベントをリスニングします.例えば、最後までスライドして自動的にロードするかどうかは、throttleで判断します.
2.例2.1ブレ止め
js

<input type="text" class="autocomplete">

//  debounce   ,http  ,        
function make_ajax_request(){
     
    //         api   
}
//         lodash debounce  
$('.autocomplete').on('keydown',
     _.debounce(make_ajax_request, 1300));
});
vue

<template>
  <input @input="debounceHandleInput"/>
</template>

<script>
import _ from 'lodash';

export default {
     
  name: 'debounce',
  data() {
     
    return {
     
      starTime: 0,
      endTime: 0,
      delay: 1000,
    };
  },
  computed: {
     
    debounceHandleInput() {
     
      return _.debounce(this.handleInput, this.delay);
    },
  },
  methods: {
     
    handleInput(e) {
     
      console.log(`debounce wait   ${
       this.delay}ms`);
      console.log('   input  ', e.target.value);
      this.startTime = new Date().getTime();
      this.remoteMethod();
    },
    remoteMethod() {
     
      setTimeout(() => {
     
        const result = `       !`;
        this.endTime = new Date().getTime();
        const costTime = this.endTime - this.startTime;
        console.log(result);
        console.log(`  ${
       costTime}  `);
      }, 2000);
    },
  },
};
</script>

    :
debounce wait   1000ms
   input   131312000  

2.2節流
js

 var throttle = function(func, delay) {
     
    var timer = null; //     ,    
    var prev = Date.now(); //           
    return function() {
     
      var context = this;   // this  window
      var args = arguments;
      var now = Date.now();
      var remain = delay - (now - prev); //     
      clearTimeout(timer);
      //         0,     
      if (remain <= 0) {
     
        func.apply(context, args);
        prev = Date.now();
      } else {
     
        timer = setTimeout(func, remain);
      }
    }
  }
  function handle() {
     
      console.log(Math.random());
  }
  var container = document.getElementById('container')
  container.addEventListener('scroll', throttle(handle, 1000));
<script>
    function throttle(fn,delay){
     
        var starttime=0;
        return function f() {
     
            var nowtime=Date.now();
            if (nowtime-starttime>delay){
     
                fn.call(document);
                // fn.call(this);
                // fn();
                starttime=nowtime;
            }
        }
    }
    document.onmousemove=throttle(function () {
     
            console.log(Math.random());
        console.log(this);
        },1000);
</script>