In daily development, we need to use throttling function and anti-shaking function in many scenarios, such as: to achieve fuzzy query input box because it needs to poll Ajax, affecting browser performance, so we need to use throttling function; To achieve the verification of mobile phone number, name and so on, often we only need to verify once, this time we need to use the anti-shake function; The realization of anti – shake function

Throttling function

As the name implies, is a function to save traffic and memory performance, can be understood as a performance optimization scheme;

For example, a faucet is dripping all the time, maybe a lot of water at once, but we want to control the frequency of the faucet to drip every 1000 milliseconds. In this case, we can use the throttling function to control it (simply understood as similar to a periodic timer).

 

// Define a global variable first
var canRun = true;
// Triggered when the browser window size changes, i.e. the window size is recalculated
window.onresize = function(){
// if canRun is false
if(! canRun){// Return directly, the following code is not executed
  return
}
// This is where canRun is true, and then assign it to false
canRun = false

// Set a timer for polling
setTimeout( function () {
// This is the thing to do
    console.log("Function throttling")
// Finally remember to reassign true and continue to let it negate
    canRun = true
// Execute every 1000 milliseconds or 1 second

  }, 1000)}Copy the code

Both the anti-shake function and the throttling function are used to improve performance optimization and user experience. The throttling function is executed several times regularly.