takeaway

The anti-shake function and throttling function, as js higher-order functions, are not only often used in work but also used in interviews. This paper will explain the implementation and use principle of throttling and anti-shake, hoping to be helpful to you.

Function image stabilization

Concept: Anti-shake refers to the execution of the corresponding callback after the event is triggered by a certain time interval (such as: 300ms), and if it is triggered again within this time interval, then the timer is reset. Anti-shake dilution function executed

Anti-shake code implementation:

 function debounce(cb, delay) {
    var timer = null;
    let delay=delay||200
    return function() {
        var context = this;
        var args = arguments;
        if(timer ! == null) {// If the timer is triggered again within the delay interval, clear the timer and restart the timer. } timer =setTimeout(function() { cb.apply(context , args); }, delay); }}Copy the code

Application scenario of the anti-shake function

  • Intelligent association;

    For example, during a search, you listen for input events in the input field, press the keyboard, and the Ajax request will be triggered. Not only is it a wasteful behavior in terms of resources, but also in practical applications, users will only request after output complete characters. At this time, it is necessary to use the anti-shake function for optimization.

  • When you do resize,scroll;

Throttling function

Concept: Function throttling means that function callbacks that were previously triggered frequently are executed once at an interval.

Implementation of the throttling function

function throttle(fn, delay) {
    var flag = true
    let delay=delay||200
    return function (params) {
      if(! flag)return
      flag = false
      let _this = this
      let args = arguments
      timmer = setTimeout(() => {
        flag = truefn.apply(_this, args) }, delay); }}Copy the code

Throttling function usage scenarios

  • Click the mouse repeatedly to trigger the mousedown(trigger only once per unit of time)
  • Listen for rolling events, such as whether to slide to the bottom to automatically load more, and throttle

summary

Throttling and anti-shaking are mainly applicable to high-frequency triggering operations. If we do not limit the time of high-frequency triggering, it will lead to frequent page rendering and/or requests, etc. Affecting the user experience, we can use debounce() and throttle() to reduce the frequency with which callbacks are penalized to achieve the desired effect and reduce the impact on the user experience.