vue的防抖和节流

一、防抖和节流的概念和使用场景

防抖(debounce):防止重复触发事件,用户在短时间内频繁触发事件时,定时器会不断清空,直到指定时间后才执行回调函数,所以用户在频繁触发事件过程中,只会执行一次回调函数。

使用场景:频繁触发事件,搜索框输入值,监听浏览器窗口resize,表单提交按钮,登录发短信等等

-------------------------------------------------------------------------------------------------------------------------------

节流(throttle):节流和防抖有点类似,节流是在规定的时间里,只执行一次,节流可以减少不断执行频率,和游戏的技能冷却时间类似。

使用场景:频繁触发事件,onscroll滚动,mousemove 等等

二、参考流程图

三、核心代码实现

防抖实现代码:

function debounce(func, wait) {
  //防抖
  let timer;
  // 在后续触发事件时,是直接触发的回调函数,不会去重新定义 timer
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, arguments);
    }, wait);
  };
}

节流实现代码:

function throttle(func, wait) {
  //节流
  let timer = null;
  //以后每次事件触发只会调用回调函数
  return function() {
    if (timer) {         //如果timer一旦赋值了就等待
      return;
    } else {
      timer = setTimeout(() => {
        func.apply(this, arguments);
        timer = null;     //函数执行完毕清空timer
      }, wait);
    }
  }
}

 使用防抖或节流的index.vue

<template>
  <div>
    <div class="contain" @mousemove="count">{{ num }}</div>
  </div>
</template>
<script>
import { debounce, throttle } from "@/assets/js/util.js";
export default {
  data() {
    return {
      num: 0
    }
  },
  methods: {
    count: throttle(function () {
      this.num++
    }, 2000),
  }
}
</script>
<style>
.contain {
  width: 100%;
  height: 100px;
  background: pink;
  font-size: 28px;
  line-height: 100px;
  color: white;
}
</style>

 封装方法到util.js

function debounce(func, wait) {
  //防抖
  let timer;
  // 在后续触发事件时,是直接触发的回调函数,不会去重新定义 timer
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, arguments);
    }, wait);
  };
}

function throttle(func, wait) {
  //节流
  let timer = null;
  return function() {
    if (timer) {
      return;
    } else {
      timer = setTimeout(() => {
        func.apply(this, arguments);
        timer = null;
      }, wait);
    }
  };
}
export { debounce, throttle };

  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值