JS function stabilization and function throttling

Problem is introduced into

Problem 1: What if you implement the DOM drag and drop function, but when you bind the drag and drop event, you find that every time the element moves a little bit, it triggers a lot of callback functions, causing the browser to get stuck?

** Problem 2: ** If a button is bound with the post event of form submission, but users sometimes click the button several times in the case of poor network conditions, causing the form to be submitted repeatedly, how to prevent the occurrence of multiple submissions?

To cope with the above scenario, there are two concepts of function stabilization and function throttling. In general:

These two methods control the number of times a function is executed on the timeline.

Function anti-skid (debounce)

Concept: the callback is executed n seconds after the event is fired. If the event is fired within n seconds, the time is re-timed.

Real-life example: If someone gets in the elevator (triggers the event), the elevator will leave after 10 seconds (executes the event listener), and if someone else gets in the elevator (triggers the event again within 10 seconds), we have to wait another 10 seconds to leave (re-timing).

Function throttling

Concept: specifies a unit time, in this unit time, only one time to trigger the event callback function execution, if in the same unit time, the event is triggered multiple times, only one time can be effective.

Examples from life: We know that the current saying is that when more than 24 pictures are played in a second, a continuous animation will be formed in human vision, so in the movie (previously, now do not know), the speed of 24 pictures per second is basically played. Why not 100 or more? Because 100 would be a waste of resources when 24 would satisfy a human’s visual needs.

Analysis diagram

Suppose that the total time we observe is 10 seconds, specifying 1 second as the minimum interval between events.

If the frequency of triggering events is0.5 s/time, then

Function anti – shaking figure

None of the events were successful because there was never a second to wait for it to be triggered again.

Function throttling figure

Because it controls at most once per second, with a frequency of 0.5s per second, an event is invalidated once per second. The final control is 1s per time

If the frequency of triggering events isS / 2 times, then

Function anti – shaking figure

S / 2 times

Function throttling figure

Again, 2s/ time is greater than the minimum time limit, so each trigger takes effect.

Application scenarios

Function stabilization has the following application scenarios:

  • Add a function to the button to prevent the form from being submitted multiple times.
  • For AJAX validation of continuous input boxes, using function stabilization can effectively reduce the number of requests.
  • judgescrollIf you slide to the bottom,Scroll event+Function image stabilization

In general, it is suitable for multiple events in one response

For function throttling, there are several scenarios:

  • Refresh rate in the game
  • Drag and drop DOM elements
  • Canvas Brush

In general, it is suitable for a large number of events to be triggered evenly by time.

The source code

Function anti – shaking:

function debounce(fn, wait) {
  var timer = null;
  return function () {
      var context = this
      var args = arguments
      if (timer) {
          clearTimeout(timer);
          timer = null;
      }
      timer = setTimeout(function () {
          fn.apply(context, args)
      }, wait)
  }
}

var fn = function () {
  console.log('boom')
}

setInterval(debounce(fn,500),1000) // Trigger the first time after 1500ms, then every 1000ms

setInterval(debounce(fn,2000),1000) // It will not trigger once (I have the function tremble to see that the skill reads the item, if the item is not read, it will fail and re-read the item)
Copy the code

The reason why we return a function is because the stabilization itself is more like a function decoration, so we do a function currying. The closure is also used, and the variable of the closure is timer.

Function of the throttle

function throttle(fn, gapTime) {
  let _lastTime = null;

  return function () {
    let _nowTime = + new Date(a)if(_nowTime - _lastTime > gapTime || ! _lastTime) { fn(); _lastTime = _nowTime } } }let fn = (a)= >{
  console.log('boom')
}

setInterval(throttle(fn,1000),10)
Copy the code

Here is a simple functional throttling implemented, resulting in a boom per second

summary

Function stabilization and function throttling control the number of times a function is executed on the timeline. Shockproof can be likened to an elevator that keeps passengers on board, and throttling can be likened to a slide show that limits the frequency of a movie.

Further reading

Github: JavaScript function throttling and function shaking application scenario analysis

SegmentFault: Function throttling and function stabilization

Github: Function throttling and function stabilization