前端节流(throttle)和防抖(debounce)的区别和用法,并封装成vue指令

一、节流(throttle)

在一定时间内(例n秒内),不管方法被调动多少次,只会在n秒后再调动第二次方法。也就是每隔n秒执行一次

应用例子:滚动页面垂直滚动条,判断是否滚动到页面底部。

var canFlag = true;
window.onresize = function(){
    console.log('resize')
    if (!canFlag) return;
    canFlag = false;
    setTimeout(function(){
        canFlag = true;
        console.log('节流');
    }, 100)
}

封装成通用方法:

function ThrottleFun(callback, time){
    let canFlag = true;
    return function(){
        if (!canFlag) return;
        canFlag = false;
        setTimeout(function(){
            canFlag = true;
            callback();
        }, time)
    }
}
// 使用
let todo = function(){
    console.log('节流');
}
let throttle = ThrottleFun(todo, 100);
window.onresize = function(){
    console.log('resize');
    throttle();
}

封装成vue自定义指令:

/***
*  节流
*  带参数:    <el-button v-debounceing="[reset,[params1,params2,...],`click`,300]"></el-button>
*  不带参数:  <el-button v-debounceing="[reset,[],`click`,300]"></el-button>
*  也可简写成:<el-button v-debounceing="[reset]"></el-button>
*/
Vue.directive('throttleing', {
    bind: function (el, binding) {
        let [fn, param = [], event = "click", time = 300] = binding.value;
        let canFlag = true;
        el.addEventListener(event, () => {
            if (!canFlag) return;
            canFlag = false;
            setTimeout(function(){
                canFlag = true;
                fn(...param);
            }, time);
        })
    }
})

二、防抖(debounce)

在一定时间内(例n秒内),不管方法被调动多少次,只执行一次方法。也就是只执行最后一次

应用例子:判断用户的输入情况,只在用户停止输入一段时间后再进行判断。

var timer;
window.onresize = function(){
    console.log('resize')
    clearTimeout(timer)
    timer = setTimeout(function(){
        console.log('防抖')
    }, 100)
}

封装成通用方法:

function DebounceFun(callback, time){
    var timer;
    return function(){
        clearTimeout(timer);
        timer = setTimeout(function(){
            callback();
        }, time);
    }
}
// 使用
let todo = function(){
    console.log('防抖')
}
let debounce = DebounceFun(todo, 100);
window.onresize = function(){
    console.log('resize');
    debounce();
}

封装成vue自定义指令:

/***
*  防抖
*  调用方法和节流相同
*/
Vue.directive('debounceing', {
    bind: function (el, binding) {
        let [fn, param = [], event = "click", time = 300] = binding.value;
        let timer;
        el.addEventListener(event, () => {
            clearTimeout(timer)
            timer = setTimeout(function(){
                fn(...param);
            }, time)
        })
    }
})
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值