Throttling function

In the scenario where a function is triggered multiple times in a short period of time, the execution function is throttled to save invalid waste

1. Application scenarios

  • In the scenario above, whenever the contents of the search box are changed, Ajax requests are made in real time and the response data is rendered to the page. Users may need to enter the content they want to search for multiple times, and requesting each time will cause unnecessary waste
  • So write a throttling function at the source that only requests the results of the last input when the contents of the search box change several times within a predetermined period of time
export function debounce(fun, delay){
  let timer / / timer
  
  return function (. args){
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimerout((a)= > { // 
      fun.apply(this, args)
    }, delay)
  }
}
Copy the code

Note: Code sourceVue-music Music player project

2. Function calls

this.$watch(
  "query",
  debounce(newQuery= > {
    // Up to 200ms function throttling
    this.$emit("query", newQuery);
  }, 200));Copy the code
  • The function is called via vue’s $watch instance method, listeninginputBox content changes, executethis.$emit("query", newQuery);Add a throttle function to the function
  • Set 200ms in the input content no longer change to request data

3. The erroneous zone

  • The closure function in debounce is not executed because it only returns a function. Instead, watch should write an anonymous function that executes automatically when listening for changes. The **debounce(newQuery,200)** function is already executed when it is written and the closure that returns is waiting to be executed
  • (… Args) represents all the parameters passed by the current function execution. When placed in the execution environment of watch, it represents the new and old parameter values monitored for changes, which is the newQuery parameter of the arrow function executed in the timer

Project address: VUe-music Music player project