函数节流和函数防抖

一、

节流Throttle:第一个人说了算
防抖Debounce: 最后一个人说了算

一般情况我们经常使用的是防抖

一、第三方库对节流和防抖的实现 - 使用lodash封装好的方法_.debounce

# npm
npm install lodash --save
#yarn
yarn add lodash
//throttling 方法
//要对事件进行节流处理方法非常简单,只需将要调用的函数包装在lodash的_.throttle函数中即可。
<template>
  <button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
<script>
import _ from 'lodash'
export default {
  methods: {
    throttledMethod: _.throttle(() => {
      console.log('I get fired every two seconds!')
    }, 2000)
  }
}
</script>

debouncing 方法
尽管节流在某些情况下很有用,但一般情况我们经常使用的是防抖。 防抖实质上将我们的事件分组在一起,并防止它们被频繁触发。 要在Vue组件中使用节流,只需将要调用的函数包装在lodash的_.debounce函数中。

<template>
  <button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
<script>
import _ from 'lodash'
export default {
  methods: {
    throttledMethod: _.debounce(() => {
      console.log('I only get fired once every two seconds, max!')
    }, 2000)
  }
}
</script>

二、直接在所属vue文件的的生命周期中封装一个方法:

//节流函数
    throttleV1(method, context) {
      clearTimeout(method.tId);
      method.tId = setTimeout(function() {
        method.call(context);
      }, 300);
    },

调用接口的部分无需改动

举例这是一个取消时调用的方法

//  取消
    cancel() {
      // ajax...逻辑操作
    },

在html部分直接调用

@click="throttleV1(cancel)"

防抖Debounce 

可定义只执行第一次或只执行最后一次

/**
 * 封装成公用方法 可在main.js中全局用用
 * @param callback 函数
 * @param duration 指定时间段内
 * @param isFirstExecution true时只执行第一次,为false时只执行最后一次
 * @returns {(function(...[*]=): void)|*}
 * @constructor
 */
let debounceTimer = null
export function Debounce (callback,duration , isFirstExecution) {
  return function (...args) {
    let ctx = this
    const delay = function () {
      debounceTimer = null
      if (!isFirstExecution) callback.apply(ctx, args)
    }
    let executeNow = isFirstExecution && !debounceTimer
    clearTimeout(debounceTimer) // 清除定时器
    debounceTimer = setTimeout(delay, duration)
    if (executeNow) callback.apply(ctx, args)
  }
}
// main.js中全局注册
import {Debounce} from '文件路径url' // 引入
Vue.prototype.$Debounce = Debounce // 全局注册
// 使用方法1 : 直接在html中页面使用  推荐使用
<button @click="$Debounce(tese1, 300, true)()">btn</button> // 方法咩有设置参数
// 方法设置了参数
<button @click="$Debounce(toConfirmSku , 300, true)('我是code')">btn</button> 
 tese1() {
     console.info(1111)
 }
 toConfirmSku (code) {
    console.log(code)
}
// 使用方法2 :js方法中使用
html中使用test方法即可
<button @click="test">btn</button>
// 先引入
import {Debounce} from '../../utils/commomUtils' // 全局注册js文件用于项目文案
test: Debounce(function () {
      console.log(1111)
    }, 3000, true),

三、可升级函数防抖和函数节流将他们封装成公用的 .vue 这样载其他的页面就可以直接import使用

注意:方法二有验证  这是在其他博主的博客上参考的

将他们封装成公用的 .vue 这样载其他的页面就可以直接import使用 (有待实践)

/**
 * 函数防抖 (只执行最后一次点击)
 * @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);
        }
    }
};

用法

...
methods:{
	getAliyunData:Throttle(function(){
	...
	 },1000),
}
...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值