前端开发那些事儿

vue的防抖和节流

2021-03-11  本文已影响0人  kattes

函数防抖

防抖分两种: (都是频繁触发事件)
一是立即执行:第一次触发时执行函数,后面触发不会执行,停止触发,间隔一定时间之后再触发事件,函数才会再次执行
二是后执行:事件只会在触发事件之后间隔定义的时间,函数才会被执行,而且只会执行最后一次触发的事件。

vue对click添加防抖处理:

// 防抖处理-立即执行
const on = Vue.prototype.$on
Vue.prototype.$on = function (event, func) {
  let timer;
  let flag = true;
  let newFunc = func
  if (event == 'click') {
    newFunc = function () {
      if(flag) {
        func.apply(this, arguments)
        flag = false
      }
      clearTimeout(timer)
      timer = setTimeout(function () {
        flag = true
      }, 500)
    }
  }
  on.call(this, event, newFunc)
}



// 防抖处理 -- 最后执行
const on = Vue.prototype.$on
Vue.prototype.$on = function (event, func) {
  let timer
  let newFunc = func
  if (event === 'click') {
    newFunc = function () {
      clearTimeout(timer)
      timer = setTimeout(function () {
        func.apply(this, arguments)
      }, 500)
    }
  }
  on.call(this, event, newFunc)
}

函数节流

事件触发后,会先执行一次事件函数,执行之后如果在规定时间间隔内再触发事件,将不出触发函数,超过规定的事件间隔后会再次触发一次,如此往复

vue对click添加节流处理

// 节流
const on = Vue.prototype.$on

Vue.prototype.$on = function (event, func) {
  let previous = 0
  let newFunc = func
  if (event === 'click') {
    newFunc = function () {
      const now = new Date().getTime()
      if (previous + 1000 <= now) {
        func.apply(this, arguments)
        previous = now
      }
    }
  }
  on.call(this, event, newFunc)
}

使用方式:
选择一种,将代码复制粘贴在main.js即可。

js方法的防抖和节流

export default {
  _debounce(fn, delay) {
    var delay = delay || 200;
    var timer;
    return function () {
        var th = this;
        var args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
        }, delay);
    };
  },
  // 节流
  _throttle(fn, interval) {
    var last;
    var timer;
    var interval = interval || 200;
    return function () {
        var th = this;
        var args = arguments;
        var now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                fn.apply(th, args);
            }, interval);
        } else {
            last = now;
            fn.apply(th, args);
        }
    }
  }
}

使用方法:

// 在需要使用的地方引用
import { public } from "@/utils/public";
changefield: public._debounce(function(_type, index, item) {
    // do something ...    
}, 200)

参考文档:
https://zhuanlan.zhihu.com/p/72923073
https://www.jianshu.com/p/30bbea9a3def
https://www.cnblogs.com/hubufen/p/13092636.html

上一篇下一篇

猜你喜欢

热点阅读