1, the difference between

The purpose of both damping and throttling is to save performance costs. The hope is that the request will not be triggered repeatedly within a certain interval. Common scenarios are used in search and web scrolling events. The differences are as follows:

  • Shaking: Execute a function for a specified period of time. If it is triggered again within that time, the timing will restart.
  • Throttling: Executes a function at a fixed time. If triggered again during this period, the timer will not restart. Only one execution can be performed during this period.

To put it in a more informal way, if you’re going to study for 60 minutes, and during that time, you’re interrupted by something outside, you start studying again for 60 minutes.

                 

Let’s say you’re going to study for 60 minutes. If you’re interrupted by external factors and you don’t want to do anything during that time, just study for 60 minutes.

2. Code implementation

    / * * *@description: Anti-shaking function *@param {function} Func callback function *@param {function} Delay Interval time *@return: function
     */    
    function antiShake(func, delay) {
      let timer // Save the timer value as a closure
      return function (. args) { 
       // If the timer already exists, clear the timer
        if (timer) { 
          clearTimeout(timer)
        }
       // Reset the timer. Note: This is a one-time timer
        timer = setTimeout(() = > {
          func.apply(this, args) }, delay); }}/ * * *@description: Throttling function *@param {function} Func callback function *@param {function} Wait Interval *@return: function
     */    
    function throttling(func, wait) {
      let timer // Save the timer value as a closure
      return function(. args) { 
        // If the timer already exists, the timer can be executed again after the scheduled time is finished
        if(! timer) { timer =setTimeout(() = > {
            func.apply(this, args)
            timer = null}, wait); }}}// Insert an Input text box to listen for Input events
    document.querySelector('input').addEventListener('keyup', antiShake(function() 	 {
      console.log('As long as you click fast enough, I won't do it.')},500))
    // Listen to the mouse move on the interface
    document.querySelector('html').addEventListener('mousemove', throttling(function() {
      console.log('1s can only be executed once ')},1000))
Copy the code

This is only a personal understanding, if there is any deficiency, please correct me.