Anti-shake, throttling and application scenarios of functions implemented in Vue

1 Introduction

1.1 Function debounce
definition: Callback will be executed n seconds after the event is triggered, and if it is triggered again within these n seconds, the timing will be restarted; (similar to the effect of returning to the city of glory of the king~~)
Typical case input search : The search request is made n seconds after the input is completed, and the time is re-timed if the content is input again within n seconds.
Implementation principle: The basic idea of ​​function anti-shake is to set a timer, clear the last timer when running the code within a specified time interval, and set another timer, until the function request stops and exceeds the time interval before execution.
scenes to be used:

  1. Search and input in the search box, and send the request after the last input is completed;
  2. Input verification of mobile phone number and email address;
  3. When window triggers resize, continuously adjusting the size of the browser window will trigger this event continuously, and use anti-shake to make it trigger only once;

1.2 Function Throttle
Definition: It is stipulated that a function can only be triggered once within a unit time. If a function is triggered multiple times within this unit time, only one time will take effect; a
typical case is triggered by continuous mouse clicks, and it is specified to be more than n seconds Only one click will take effect.
Implementation principle: The principle is to use the timestamp to judge whether the execution time of the callback is reached , record the last executed timestamp, and then execute the callback every time the scroll event is triggered, and in the callback, judge whether the current timestamp is between the last execution timestamp and the interval The specified time period has been reached, if it is, execute it and update the time stamp of the last execution.
scenes to be used:

  1. Implementation of drag and drop function of DOM elements (mousemove);
  2. Multiple clicks to submit the form;
  3. Calculate the distance moved by the mouse (mousemove);
  4. Canvas simulation drawing board function (mousemove);
  5. Mousedown/keydown events of shooting games (only one bullet can be fired per unit time);
  6. Scroll loading, load more operations;

2. Code implementation

In Vue2.x, we write the anti-shake and throttling functions in the utils folder for easy reference when needed

// 防抖
function _debounce(fn, delay = 500) {
    
    
  var timer = null;
  return function () {
    
    
    var _this = this;
    var args = arguments;
    if (timer) clearTimeout(timer); 
    timer = setTimeout(function () {
    
    
      fn.apply(_this, args);
    }, delay);
  };
}

// 节流
function _throttle(fn,delay = 1000){
    
    
  var lastTime, timer, delay;
  return function(){
    
    
    var _this = this;
    var args = arguments;
    var nowTime = Date.now(); 
    if(lastTime && nowTime - lastTime < delay){
    
    
      if (timer) clearTimeout(timer); 
      timer = setTimeout(function(){
    
    
        lastTime = nowTime;
        fn.apply(_this,args);
      },delay)
    }else{
    
    
      lastTime = nowTime;
      fn.apply(_this,args);
    } 
  }
}  

export {
    
    
  _debounce,
  _throttle,
}

Reference in components

<template>
  <div class="about">
    <el-input v-model="inputVal" placeholder="请输入内容" @input="inputChange"></el-input>
  </div>
</template>

<script>
import {
    
    _debounce, _throttle} from '@/utils/index.js'
export default {
    
    
  data() {
    
    
    return {
    
    
      inputVal:'',
      count:0,
    };
  },
  methods: {
    
    
    // input值改变时触发
    inputChange:_debounce(function(){
    
    
      console.log(this.inputVal)
    },1000),
    // 滚动条滚动时触发
    scroll(){
    
    
      this.count += 1;
      console.log('scroll触发了'+ this.count +'次')
    }
  },
  mounted() {
    
    
    window.addEventListener('scroll', _throttle(this.scroll,5000));
  },
};
</script>

<style lang="stylus" scoped>
.about{
    
    
  width:100%;
  height:800px;
}
</style>

Portal: the use of anti-shake in the Element-ui selector (Select)

Guess you like

Origin blog.csdn.net/ZYS10000/article/details/112004946