vue防抖节流函数

节流和防抖常用与监听滚动事件,移动事件,窗口改变大小事件,输入事件等高频触发事件,当事件处理函数较为复杂时,将导致无法实时响应,降低用户体验度,影响效率,出现页面卡顿,假死等现象。

debounce 周期内有新事件触发,清除旧定时器,重置新定时器;这种方法,需要高频的创建定时器。

throttling 周期内有新事件触发时,重置定时器开始时间撮,定时器执行时,判断开始时间撮,若开始时间撮被推后,重新设定延时定时器。

1.定义模块文件并导出防抖函数和节流函数

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const Debounce = (fn, t) => {
    let delay = t || 500;
    let timer;
    console.log(fn)
    console.log(typeof fn)
    return function () {
        let args = arguments;
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            fn.apply(this, args);
        }, delay);
    }
};
/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (fn, t) => {
    let last;
    let timer;
    let interval = t || 500;
    return function () {
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    }
};

2.在组件中导入函数

import {
		Debounce,
		Throttle
	} from '@/common/config/debThr.js';

3.methods中调用

...
methods:{
/*
    小提示:不要写成回调函数的形式 this指向改变了
*/
	getAliyunData:Throttle(function(){
	...
	 },1000),
}
...

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值