防抖节流在vue中的使用

//防抖
function debounce3(fn, wait, isImmediate = false) {
    let timerId = null;
    let flag = true;
    return function () {
        let context = this
        let args = arguments
        clearTimeout(timerId)
        if (isImmediate) {
            if (flag) {
                fn.apply(context, args)
                flag = false
            }
            timerId = setTimeout(function () {
                flag = true
            }, wait)
        } else {
            timerId = setTimeout(function () {
                fn.apply(context, args)
            }, wait)
        }
    }
}


//节流
let throttle = (fn,delay) => {
	//进入的时间,其实就是用户什么时候 触发 的 滚动条
	let enterTime = 0; 
	let gapTime = delay || 200; //间隔时间
	return function(){
		let context = this;
		//第一次 执行 return 里面的匿名函数方法的时间
		let backTime = new Date(); 
		// 用户 触发 到 执行是需要时间的,因此 如果 执行匿名函数方法的时间 减去 出发的时间 大于间隔的时间,就进行函数的触发;
		if(backTime - enterTime > gapTime){ 
			fn.apply(context,arguments);
			//把执行匿名函数方法的时间保存 到 触发的时间,以便 第二次运行函数
			enterTime = backTime 
		}
	}
}

export {
    debounce3,throttle 
}




V3使用

//页面使用
<button @click="b(666)">
  123
</button>
const b=debounce3(function(i){
console.log(i,bbb.value);
},2000,true)


const b=throttle(function(i:number){
console.log(bbb.value);
},2000)

V2

<button @click="b('444')">d</button>


b:debounce3(function(i){
console.log(i,this.mod);
},2000,true),


b:throttle(function(i){
console.log(i,this.mod);
},8000),

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值