防抖处理和节流处理

函数防抖(debounce):

在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时;典型的案例就是输入搜索:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时。

使用场景:

1.频繁操作点赞和取消点赞,因此需要获取最后一次操作结果并发送给服务器

2.input输入框多次请求的问题

3.登录、发短信等按钮,避免用户点击太快,以致于发送了多次请求,需要防抖

4.调整浏览器窗口大小时,resize 次数过于频繁,造成计算过多,此时需要一次到位,就用到了防抖

5.文本编辑器实时保存,当无任何更改操作一秒后进行保存

函数节流(throttle):

规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效; 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效。

使用场景:

1.scroll事件,每隔一秒计算一次位置信息等

2.浏览器播放事件,每个一秒计算一次进度信息等

3.input框实时搜索并发送请求展示下拉列表,每隔一秒发送一次请求(也可做防抖)

我们将防抖和节流函数写在utils文件夹下面需要的时候引用

export function _debounce(fn, delay) {
//防抖
  var delay = delay || 200;
  var timer;
  return function () {
    var th = this;
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}
// 节流
export function _throttle(fn, interval) {
  var last;
  var timer;
  var interval = interval || 200;
  return function () {
    var th = this;
    var args = arguments;
    var now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        last = now;
        fn.apply(th, args);
      }, interval);
    } else {
      last = now;
      fn.apply(th, args);
    }
  }
}

  

引用

<template>
    <div>
        <input type="button" value="+1" @click="add">
        <br>
        <input type="button" value="-1" @click="reduce">
    </div>
</template>

<style>
    input{
        width: 200px;
        height: 20px;
    }
</style>

<script>
  import { _debounce } from '@/utils/debounce'
  import { _throttle } from '@/utils/debounce'
  import { mapState, mapActions } from 'vuex'
    export default {
      computed: {
        ...mapState({
//          kindlist: ({ kind: { kindlist } }) => kindlist, //{ kind: { kindlist } }=state.kind,kindlist
//          brandlist: (state) => state.kind.brandlist,
//          prolist: ({ kind }) => kind.prolist  //kind=state.kind
          count:(state)=>state.count.count,
        })
      },
      methods:{
        add:_debounce(function(_type, index, item){  //防抖
           this.$store.dispatch('count/add')
        },2000),
        reduce:_throttle(function(){
            this.$store.dispatch('count/reduce')
          },2000)
        },
    }
</script>

  

 

posted @ 2021-10-13 14:39  ssssd12  阅读(147)  评论(0)    收藏  举报