vue节流和防抖的理解

节流
定义:规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效;
就像游戏技能CD,有冷却时间,过了规定的时间,才可以再次触发技能
防抖
定义:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时
就像砸门开关,如果车辆在规定的时间里一直过,砸门就会一直开着,如果过了最后一辆车,规定的时间里没有其他车来,就会关上砸门,防止用户频繁触发一个事件,只执行该事件的最后一次

在vue中使用创建一个文件util.js

function debounce(func, wait) {
  //防抖  防止用户频繁触发一个事件,只执行该事件的最后一次   就像砸门  在规定的时间里可以 一直通过  最后一次通过 过了规定时间 就会关上 砸门 输入的监听
  let timer;
  // 在后续触发事件时,是直接触发的回调函数,不会去重新定义 timer
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, arguments);
    }, wait);
  };
}
 
function throttle(func, wait) {
  //节流  就像控制游戏技能CD  冷却时间 待时间过后  又可以执行下一次的技能  提交表单使用
  let timer = null;
  return function() {
    if (timer) {
      return;
    } else {
      timer = setTimeout(() => {
        func.apply(this, arguments);
        timer = null;
      }, wait);
    }
  };
}

export { debounce, throttle };


其他组件使用

<template>
	<div >
	<el-input v-model="inputVal" placeholder="请输入内容" @input="inputChange"></el-input>
	<el-button @click="clickDebounce">防抖</el-button>
	<el-button @click="clickThrottle">节流</el-button>
	</div>
</template>
<script>
import { debounce, throttle } from "@/assets/js/util.js";
export default {
 data() {
	 return {
			 inputVal:'',
		 };
   },
 methods: {
	// input值改变时触发  防抖测试
	inputChange:debounce(function(){
		console.log(this)
		console.log(this.inputVal)
     },2000),
	 //防抖  就像砸门  在规定的时间里可以 一直通过  最后一次通过 过了规定时间 就会关上 砸门
	clickDebounce: debounce((e) => {
			//console.log(this) //undefined  注意这里的用法和this 
	      console.log(1)
	    }, 2000),
	//节流  就像游戏技能CD 冷却时间  到了时间之后 就会执行下一次的技能
	clickThrottle: throttle((e) => {
	  console.log(2)
	}, 2000),

   },


}
</script>

第一次立即执行 utildeth.js

// let btn=document.getElementById('btn')
// let btn1=document.getElementById('btn1')

// //一般常用方法
// btn.οnclick=debounce(function(){
//    console.log(111)
// },2000,true)

//防抖
// 在一个周期T内,如果重复的进行某种响应操作,在不设置防抖函数的时候,每操作一次都会调用一遍响应函数。设置了防抖函数,如果这一次操作与上一次操作的间隔小于T,则不会调用响应函数,
//并让计时器重新从0开始计时,直到某次操作与上次操作间隔大于等于T,才执行。

/*
 * @param  {function}   func      回调函数
 * @param  {number}     wait      表示时间间隔
 * @param  {boolean}    immediate  如果为true则为立即执行,为false则为延迟执行                             
 * @return {function}             返回客户调用函数
 */
 function debounce(func,wait,immediate) {
    let timeout,result; // timeout 为计时器,result为回调函数的返回值
    let debounced = function() {
        if(timeout)clearTimeout(timeout); // 如果计时器存在,要将其清除,以便重新建立新的计时器(防抖的核心)
        let context = this; // 暂存debounced的this指向,其指向响应函数,方便后续改变func的this指向
        let args = arguments; // 暂存响应函数的event参数,以便后续将其赋给fun
        if(immediate) {
            let flag = !timeout; // 判断此时是否还在上一个计时中
            timeout = setTimeout(function(){
                timeout = null;
            },wait);   // 设定计时器,在wait时间之后,把计时器赋为空,以便那时能立即执行
            if(flag) result = func.apply(context,args); // 若满足条件,则立即执行
        }else {
            // 不是立即执行模式则设置延迟执行函数
            timeout = setTimeout(function() {
                func.apply(context,args);
            },wait);  
        }
        return result;
    }
    // 取消计时器的操作
    debounced.cancel = function() {
        clearTimeout(timeout);
        timeout = null;
    }
    return debounced;
}





//一般常用方法
// btn1.οnclick=throttle(function(){
//    console.log(111)
// },2000, {leading:true,trailing:false})


// options的选项,options选项有三种,为

// 第一次立即执行,最后一次不执行 {leading:true,trailing:false}
// 第一次立即执行,最后一次执行 {leading:true,trailing:true}
// 第一次不立即执行,最后一次执行 {leading:false,trailing:true}
// 注:当设置为{leading:false,trailing:false} 时,函数并不会显示出应有的效果,而会显示出类似{leading:true,trailing:false}的效果,但是仍有区别,区别在于第一次不是立即执行。



//节流
// 节流与防抖有相似之处,本质上来说两者都是为了防止前端频繁进行响应操作而设置的,二者的差别在于防抖会在某次操作重新进行计时,
// 而节流则不会,节流是从第一次操作开始计时,周期性的判断是否有响应,如果有则执行

/*
 * @param  {function}   func      回调函数
 * @param  {number}     wait      表示时间窗口的间隔
 * @param  {object}     options   如果想忽略开始函数的的调用,传入{leading: false}。
 *                                如果想忽略结尾函数的调用,传入{trailing: false}
 *                                两者不能共存,否则函数不能执行
 * @return {function}             返回客户调用函数
 */
 function throttle(func, wait, options) {
    let context, args, timeout;
    let old = 0; // 时间戳
    if (!options) options = {}; // 如果没有该参数,则置为0,防止意外发生
    return function () {
        context = this;
        args = arguments;
        let now = new Date().valueOf();
        if (options.leading === false && old == 0) old = now; // 不要立即执行,则第一次不会进入if(now-old>wait)
        if (now - old > wait) {   // 当时间间隔达到一个周期则执行此代码块
            // 第一次会直接执行
            if (timeout) {            // 将计时器清除,防止执行两次响应函数
                clearTimeout(timeout);
                timeout = null;
            }
            func.apply(context, args);
            old = now;
        } else if (!timeout && options.trailing !== false) { // 当时间间隔未达到一个周期时则执行此代码块
            // 最后一次被执行
            timeout = setTimeout(function() {  // 在一般情况下是不会执行这个延迟函数的,只有在最后一次执行此延迟函数
                old = new Date().valueOf();    // 在最后一次执行时候将old置为当前时间,防止下一次操作响应的时间间隔不足wait
                timeout = null;
                func.apply(context, args);
            }, wait)
        }
    }
}

export { debounce, throttle };

其他组件使用

import {debounce,throttle} from "@/assets/js/utildeth.js";
export default {
 methods:{
	 getData: debounce(function() {
		  	this.loading=true;
		  	this.$axios.get(`/gw/forwarder/${this.currentPage}`).then((res) => {
		      
		  		this.tableData = res.rows;
		  		this.total = res.count;
		  
		  	}).finally(()=>{
		  		this.loading=false;
		  	})
		  }, 2000,true),
	  }
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时光浅止

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值