19. The difference between throttling and anti-shake and understanding of application scenarios

Throttling and anti-shake

  • What is the difference between throttling and anti-shake?
  • What scenarios are throttling and anti-shake used for?

Throttling (throttle) and anti-shake (debounce) are two commonly used browser event handling methods.

Same point:

  1. All are to reduce the frequency of event triggering and optimize performance.

difference:

  1. Throttling refers to triggering an event at most once within a period of time. The throttling algorithm will determine whether to trigger an event within a specific time interval;
  2. Anti-shake means that as long as an event is triggered within a period of time, the time is recalculated, and the event is not actually executed until no event is triggered within this period;
  3. Throttling is suitable for continuous triggering, and anti-shake is suitable for a large number of triggers in a short period of time.

Anti-shake (debounce)

  Anti-shake is a browser event processing method. In layman's terms, it is the process of actually executing the event only after the last event is triggered when a large number of events are triggered in a short period of time.

In layman's terms: anti-shake, prevent shaking "You shake first, when it stops, then take the next step."

Insert image description here

For example, when the user quickly enters a search keyword, the browser will execute the event handler only every500ms. This means that when the user is typing quickly, the browser will continuously recalculate the time to execute the event, and the event processing function will not be actually executed until the user stops typing within 500ms.

The advantage of this is that it prevents a large number of unnecessary events from being triggered and has a good optimization effect on performance.

Code implementation (code)

function debounce(fn, delay = 200) {
    
    
    let timer = 0
    
    return function () {
    
    
        if (timer) clearTimeout(timer)
        
        timer = setTimeout (() => {
    
    
            fn.apply(this,arguments) // 透传this 和参数
            timer = 0
        },delay)
    }
}

Case test (test)

Monitor the input box and the processing effect of the anti-shake function when the user quickly inputs content.

Before anti-shake:

<body>
  搜索:<input id="input1"/>
  <script>
    function debounce(fn, delay = 200) {
      
      
    let timer = 0
    
    return function () {
      
      
        if (timer) clearTimeout(timer)
        
        timer = setTimeout (() => {
      
      
            fn.apply(this,arguments) // 透传this 和参数
            timer = 0
        },delay)
    }
}

const input1 = document.getElementById('input1')

input1.addEventListener('keyup',(e) => {
      
      
  console.log(e.target.value)
})
  </script>
</body> 

Effect:

Insert image description here


After anti-shake:

<body>
  搜索:<input id="input1"/>
  <script>
    function debounce(fn, delay = 200) {
      
      
    let timer = 0
    
    return function () {
      
      
        if (timer) clearTimeout(timer)
        
        timer = setTimeout (() => {
      
      
            fn.apply(this,arguments) // 透传this 和参数
            timer = 0
        },delay)
    }
}

const input1 = document.getElementById('input1')

input1.addEventListener('keyup',debounce((e) => {
      
      
  console.log(e.target.value)
},300))
  </script>
</body>

Effect:

Insert image description here


Comparison results: Anti-shake filters out many unnecessary event triggers, and only prints the result of the input box after the user inputs300ms, reducing browser performance consumption.


Throttle

  Throttling is a browser event handling method. In layman's terms, it is the process of limiting events to trigger at most once within a specific period of time.

  Throttling, saving interactive communication, flow, does not necessarily refer to traffic

In layman's terms: "Don't be anxious, come one by one, follow the time rhythm, and those who jump in line will be invalid."

Insert image description here

For example, when the user continues to scroll the mouse wheel, the browser triggers the event handler every100ms. This means that no matter how fast the user scrolls, the event handler will only be triggered at most once every100ms.

The advantage of this is that it prevents events from being triggered too frequently and has a good optimization effect on performance.

Code implementation (code)

function throttle(fn, delay = 100) {
    
    
    let timer = 0 
    return function () {
    
    
		if (timer) return
        
        timer = setTimeout(()=> {
    
    

            fn.apply(this,arguments) // 透传this 和参数
        	timer = 0
        },delay)
    }
}

Case test (test)

Monitor the position information of elements and the effect of throttling function processing in drag and drop projects.

Before throttling:

<body>

  <div id="drag" draggable="true" style="width: 100px ;height: 50px; background-color: brown; padding: 10px;">
    可拖拽
  </div>

  <script>
    function throttle (fn, delay = 100) {
      
      
      let timer = 0
      return function () {
      
      
        if (timer) return

        timer = setTimeout(() => {
      
      

          fn.apply(this, arguments) // 透传this 和参数
          timer = 0
        }, delay)
      }
    }

    const div1 = document.getElementById('drag')

    div1.addEventListener('drag',(e) => {
      
      
      console.log('拖拽的位置:',e.pageX,e.pageY)
    })
  </script>
</body>

Effect:

Insert image description here


After throttling:

<body>

  <div id="drag" draggable="true" style="width: 100px ;height: 50px; background-color: brown; padding: 10px;">
    可拖拽
  </div>

  <script>
    function throttle (fn, delay = 100) {
      
      
      let timer = 0
      return function () {
      
      
        if (timer) return

        timer = setTimeout(() => {
      
      

          fn.apply(this, arguments) // 透传this 和参数
          timer = 0
        }, delay)
      }
    }

    const div1 = document.getElementById('drag')
    
    div1.addEventListener('drag',throttle((e) => {
      
      
      console.log('拖拽的位置:',e.pageX,e.pageY)
    },300))
      
  </script>
</body>

Effect:

Insert image description here


Comparison results: Throttling prevents frequent event triggering. Only during the user dragging process, the position information of the element is printed every 300ms, which reduces the performance of the browser. consumption.


Summarize

  • Throttling: Limit execution frequency, rhythmic execution

  • Anti-shake: limit the number of executions, multiple intensive triggers will only be executed once

  • Throttling focuses on the "process", and anti-shaking focuses on the "result"

  • For actual work, I still use lodash The tool library is better

Guess you like

Origin blog.csdn.net/qq_36362721/article/details/128927798