preface

This series is a collection of front-end handwriting functions that need to be mastered by the author. The hand tearing of these functions requires certain front-end basic skills, which will also appear frequently in the interview. The author will present each handwriting function as a separate article, which is as meticulous as possible without making the article too long or too messy. This article is for the tool function anti-shake and throttling function that is often used in front-end development

Image stabilization function

What is an anti-shake function

Image stabilization function is the function of realization, function can delay the triggered, at the same time in a certain time trigger updates the delay time for many times, finally realizes the effect is, in a certain period of time triggered multiple image stabilization function, finally the function will only perform the final that once triggered, if the game do metaphor, so if you can be understood as to skills increase casting before action, If the forward swing is interrupted, you need to re-cast

The application scenario of the anti-shake function

In what situations do you need to use an anti-shake function? The following is a simple list of a few basic examples, thinking about the characteristics of these use scenarios, so that in the future their own reasonable use of the anti-shake function

  1. Input validation or dynamic search

In the input box, whether it is to verify the content entered by the user, or to recommend the content according to the keywords entered by the user after querying, we generally need to monitor the input of the user. If we verify or send a request after each character entered by the user, it will greatly consume resources

  1. The drop-down refresh

Refresh data when the user is pulling down. Assuming that the user is pulling down quickly and meaninglessly (think about how often you are pulling down to refresh the page when your network is bad or bored), listening for the pull down every time and then making a data request is also a huge resource drain

  1. Button to submit

If the user mistakenly touches the connection point and submits the form for several times during button submission, more resources will be consumed. If the operation is non-idempotent, other unexpected problems will occur with improper processing

  1. Listen for page scrolling

Sometimes we want the page to perform an action while scrolling to a certain point, such as asking for specified data or loading a special entry animation. If we listen for the page to scroll directly, the page will continue to listen for function callbacks every time the page scrolls, which also hurts performance

The above are the basic application scenarios of some anti-shake functions provided by the author. Of course, anti-shake is not the only solution in these scenarios, and in some cases, multiple means are needed for processing, but it cannot be denied that the anti-shake function is simple and efficient to use in these scenarios

The realization of anti – shake

Next we will start from the basic idea step by step, and finally achieve a tremble function

Business scenario: Monitor the keywords entered by users to query relevant recommendation data, and then display the results. This is a common scenario. Generally, dynamic display of results is performed on the list search page according to the keywords entered by users

First, we complete basic functions, listening to user input and then dynamically obtaining data

  <input type="text" oninput="handleInput(this.value)">
  <script>
    // Listen for user input
    function handleInput(value) {
      mockRequestFn(value).then(res= > {
        console.log('Key words'${value}"The requested data is', res.data)
      })
    }
    
    // Simulate a request function
    const mockRequestFn = function (value) {
      // Here we simulate the request directly using Promise and setTimeout
      return new Promise((resolve, reject) = > {
        setTimeout(() = > {
          const result = {
            status: 'ok'.code: 200.data: [{ name: 'someGoods'.price: 110 }]
          }
          resolve(result)
        }, 500)})}</script>
Copy the code

Two: the first feature of anti – shake, can be triggered function delay execution. You must have thought of setTimeout, so let’s use setTimeout to do this step

    function handleInput(value) {
      setTimeout(() = > {
          mockRequestFn(value).then(res= > {
            console.log('Key words'${value}"The requested data is', res.data)
          })
      }, 1000);// Let's say the delay is 1 second
    }
Copy the code

Three: Now it’s delayed execution, but the event handler is still fired frequently, and now we have to deal with the problem of resetting the delay time when the function is fired multiple times. The so-called reset delay time is essentially canceling the last execution if the last one has not been fired. In this case, each function trigger execution is done with setTimeout, so you can use the clear timer to terminate the previous function

    let timer = null
    function handleInput(value) {
      clearTimeout(timer) // Clear the previous timer while the function is executing to reset the time
      timer = setTimeout(() = > {
        mockRequestFn(value).then(res= > {
          console.log('Key words'${value}"The requested data is', res.data)
        })
      }, 1000)}Copy the code

The basic idea of anti-shake is like this, but the current implementation method is far from enough, there are the following problems:

  1. First of all, this way of writing, can not be repeated many times, other places need to use, need to write again, resulting in code duplication, we need to encapsulate it as a function to use

  2. To achieve this function, we define the global variable timer directly and then use the defined global variable in the function, so that the function execution result is not controllable (influenced by the external timer), and the timer will pollute the global variable

  3. In some cases, image stabilization treatment function is need to be executed immediately, to perform processing function for image stabilization operation, such as when the image stabilization function using the form is submitted in operation, the user first click submit, we will not request delay, or it will greatly affect the user experience (the real image stabilization time not so long as in our example, But even in the case of image stabilization time is very short, delayed the time of image stabilization to request again, also can affect the user experience, specific is executed immediately or delay to perform, the need to choose according to the specific scene), the effect of case we need to is that users continue to input, requests for image stabilization is not one but the user stop input (after stabilization time no operation), to request data at once, This is an action that is deferred.

  4. If the buffered function has a return value, it needs to return its return value

After finding the above problems, we will package the anti-shake operation into a function for further treatment

Image stabilization function

* @param {Function} fn Function that needs to be processed for stabilization * @param {Number} time Stabilization time * @param {Boolean} triggleNow Whether to trigger immediately * @returns */ function debounce(fn, time, triggleNow) {let timer = null; return function () { let _self = this, args = arguments, result = null; if (timer) { clearTimeout(timer); } if (triggleNow) {/** * 1. Then set timer to null * 3 again after the anti-shake time. If the function is triggered again within the time it has been buffeted, clearTimeout will cancel the previous operation that set timer to null, and the timer will have a value * 4. */ const exec =! timer; timer = setTimeout(() => { timer = null; }, time); if (exec) { result = fn.apply(_self, args); } } else { timer = setTimeout(() => { result = fn.apply(_self, args); }, time); } return result; }}Copy the code

Throttling function

In fact, the throttling function and a part of the anti – shake function are thought through, let’s briefly introduce the following

What is a throttling function

When we introduced the anti – shake function, we used a metaphor, the anti – shake function is like the skill forward shake, so the throttle function can be understood as the skill cooling. This is because the throttling function is designed to execute only once in a fixed period of time if the function is fired multiple times

Note again the difference between anti-shake and throttling:

Anti-shake: set the interval time, trigger the function multiple times within the interval time, refresh the interval time, only execute the last trigger once (if it is triggered immediately, only trigger the first one)

Throttling: Sets the interval, triggers the function multiple times during the interval, triggers the function only once, after the next interval, will be executed again, and so on

Throttling Usage Scenarios

Although throttling and anti-shock functions are different, there are some scenarios in which both can be used, depending on what effect you want to achieve. For example, when the user clicks on a form submission, can throttling be used in this scenario

Here are a few scenarios where throttling might be appropriate

  1. Scene scale

When scaling the page (scene), we need to monitor the browser’s resize,scroll and other operations. If we keep listening and then do business, it will consume performance. Here we can use throttling to optimize performance

  1. The user continues to click the mouse

This scenario is very broad and can be used in any scenario that allows the user to keep clicking, but wants to fire the handler only once at a certain time

  1. Page bottom loading more

Throttling can be used when the page hits bottom and requests more data to load, but the user may hit bottom several times and send requests before the request comes back and the list is rendered again

Implementation of throttling

Because of being the implementation of the train of thought, the throttle is not as detailed narration, the realization of the throttle is that with throttling set time, event handler triggered last time, the current calculation and comparison triggering time event handler, if the event handler triggered two intervals of time is greater than the throttle, can perform functions, or continue to wait for

Throttling function

Throttling function in the implementation, there is a point to note, is whether you need to continue to perform the final trigger events, there are times when we are in the throttling operation, if again in the throttle time trigger event handler, while the function in the time period was not performed again, but logged on to the next throttling cycle, Sometimes we don’t want to do this, so we need to make parameter judgments.

/** * Throttling function *@param {Function} Fn the function that requires throttling processing *@param {Number} Delay Throttling time *@param {Boolean} NeedLast whether to perform the last trigger *@returns Fn Execution result */
function throttle (fn, delay, needLast) {
  let timer = null,
    beginTime = new Date().getTime();
  return function () {
    let _self = this,
      args = arguments,
      curTime = new Date().getTime(),
      result = null;
    clearTimeout(timer)
    // Execute the function if the interval is longer than the set time
    if (curTime - beginTime >= delay) {
      result = fn.apply(_self, args);
      beginTime = curTime;
    } else {
      // If the setting needs to be executed for the last time, then use setTimeout to defer execution
      if (needLast) {
        timer = setTimeout(() = >{ result = fn.apply(_self, args); }, delay); }}return result
  }
}
Copy the code

conclusion

The anti-shake function and throttling function themselves do not involve any knowledge related to design mode, but are only technical tool functions, which are suitable for some front-end business scenarios. Although there is not much code and it is relatively simple to implement, it also requires front-end developers to grasp the basic knowledge of JS solid enough. Since it also involves closures, apply (this refers to correlation), arguments, clearTimeout, and indicators, it also involves functional programming paradigms and the use of pure functions, any of which is worth further understanding. Therefore, in the next chapter, I will sort out the basic implementation of this and call, apply and bind in JS, which will be attached at the end of this article. Event Emitter/ Publish/subscribe