函数防抖与函数节流(vue实例)

2022-08-09,,,,

1.函数防抖(debounce)

    函数防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

    简单的说,当一个动作连续触发,则只执行最后一次。

    打个比方,坐公交,司机需要等最后一个人进入才能关门。每次进入一个人,司机就会多等待几秒再关门。

    关门这个动作,在3秒内没人上车(重复触发)才能执行

 const _.debounce = (func, wait) => {

  let timer;

 

 

  return () => {

    clearTimeout(timer);

    timer = setTimeout(func, wait);

  };};

 

 

function debounce(func, delay) {

    var timeout;

    return function(e) {

        console.log("清除",timeout,e.target.value)

        clearTimeout(timeout);

        var context = this, args = arguments

        console.log("新的",timeout, e.target.value)

        timeout = setTimeout(function(){

          console.log("----")

          func.apply(context, args);

        },delay)

    };};

 

 

var validate = debounce(function(e) {

    console.log("change", e.target.value, new Date-0)}, 380);

 

 

// 绑定监听

document.querySelector("input").addEventListener('input', validate);

 

应用场景:

* 滚动加载,加载更多或滚到底部监听

* 谷歌搜索框,搜索联想功能

* 高频点击提交,表单重复提交

 

2.函数节流(throttle)

    限制一个函数在一定时间内只能执行一次。

    举个例子,乘坐地铁,过闸机时,每个人进入后3秒后门关闭,等待下一个人进入。

 

 const _.throttle = (func, wait) => {

  let timer;

 

 

  return () => {

    if (timer) {

      return;

    }

 

 

    timer = setTimeout(() => {

      func();

      timer = null;

    }, wait);

  };};

 

 

 

function throttle(fn, threshhold) {

var timeout

var start = new Date;

var threshhold = threshhold || 160

return function () {

 

 

var context = this, args = arguments, curr = new Date() - 0

clearTimeout(timeout)//总是干掉事件回调

if(curr - start >= threshhold){

     console.log("now", curr, curr - start)//注意这里相减的结果,都差不多是160左右

     fn.apply(context, args) //只执行一部分方法,这些方法是在某个时间段内执行一次

     start = curr

}else{

//让方法在脱离事件后也能执行一次

     timeout = setTimeout(function(){

        fn.apply(context, args)

     }, threshhold);

    }

  }}var mousemove = throttle(function(e) {

console.log(e.pageX, e.pageY)});

 

 

// 绑定监听

document.querySelector("#panel").addEventListener('mousemove', mousemove);

 

总结:

    throttle:将一个函数的调用频率限制在一定阈值内,例如 1s 内一个函数不能被调用两次。

    debounce:当调用函数n秒后,才会执行该动作,若在这n秒内又调用该函数则将取消前一次并重新计算执行时间,举个简单的例子,我们要根据用户输入做suggest,每当用户按下键盘的时候都可以取消前一次,并且只关心最后一次输入的时间就行了

3.三种环境下,mousemove事件执行分布图

 

 

 

 

 

 

 

vue实例:

    imgIndex: 1,

      //节流函数存储定时器id,有值则有正在进行的函数,返回return;  无值则放行

      throttleId: null,

      //节流事件间隔=>小于300ms重复触发不执行

      delay: 300

   /**

     *节流函数,method待执行的函数,arg为该函数参数arguments

     */

    throttle(method, arg) {

      if (this.throttleId) {

        return;

      }

      method(arg);

      this.throttleId = setTimeout(() => {

        this.throttleId = undefined;

      }, this.delay);

    }

      //调用节流函数,参数为要执行的函数

      this.throttle(this.MouseWheel);

 

 

 

 

 

 

本文地址:https://blog.csdn.net/qq_42288851/article/details/107164596

《函数防抖与函数节流(vue实例).doc》

下载本文的Word格式文档,以方便收藏与打印。