Function image stabilization

Function stabilization: A function that fires so frequently that it fires only one last time within a specified period of time. For example: - Avoid sending requests every time the user enters the search box. - Avoid sending multiple requests when the user clicks the login and SMS buttons too fast. So the key is to zero out for example if you send a login request a second after the login button is clicked we can create a timer that clears the timer every time the user clicks and resets the timer so that you don't have to send a request for a second because the user is clicking too often and here's the codeCopy the code
/** ** function *@param Fn is the function to execute *@param Delay Indicates the delay time */
function debounce(fn, delay) {
  var timer = null;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() = > {
      fn.call(this);
    }, delay);
  };
}
Copy the code

Function of the throttle

Function throttling: After a function is executed once, it is executed twice only after the specified execution period. For example, the -scroll time recalculates the position every 1s instead of all the time. - Browser playback time recalculates the playback progress every 1s. Two times, lastTime and nowTime, are required to calculate the time difference to determine whether the event is executed. First, lastTime is initialized to 0 and then the system time is taken to determine whether the event is greater than delay. If so, the event is executed and nowTime is assigned to lastTime to complete throttlingCopy the code
/** * Throttling function *@param Fn is the function to execute *@param Delay Indicates the delay time */
function throttle(fn, delay) {
  var lastTime = 0;
  return function () {
    var nowTime = Date.now();
    if (nowTime - lastTime > delay) {
      fn.call(this); lastTime = nowTime; }}; }Copy the code