美文网首页
防抖节流

防抖节流

作者: hszz | 来源:发表于2021-10-18 03:51 被阅读0次

防抖 debounce

设定一个定时器, 事件在该时间内再次被触发,刷新定时器,直到最后一次触发才会触发该事件

节流 throttle

在规定时间内,无论事件被触发多少次,只会触发一次。

使用loadsh工具库

  • npm install lodash --save
<template>
  <div>
    <div>使用loadsh的方法</div>
    <button @click="testD()">防抖</button>
    <button @click="testT()">节流</button>
  </div>
</template>
<script>
import debounce from "lodash/debounce";
import throttle from "lodash/throttle";
export default {
  data() {
    return {};
  },

  methods: {
    testD: debounce(() => {
      console.log("防抖函数执行");
    }, 1000),

    testT: throttle(() => {
      console.log("节流函数执行");
    }, 2000),
  },
};
</script>

在vue中自定义实现

<!-- 自定义防抖节流 -->
<template>
  <div>
    <div class="">自定义防抖节流</div>
    <!-- 设定一个定时器, 事件在该时间内再次被触发,刷新定时器,直到最后一次触发才会触发该事件-->
    <button @click="debounce_diy()">防抖debounce</button>
    <!-- 在规定时间内,无论触发多少次事件,只会触发一次。 -->
    <button @click="throttle_diy()">节流throttle</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      timeD: 0,

      lastTime: new Date(),
    };
  },

  methods: {
    // 防抖,在半秒内再次触发会刷新定时器
    debounce_diy() {
        if(this.timeD) {
            clearTimeout(this.timeD)
        }
        this.timeD = setTimeout(() => {
            console.log("防抖操作,发送api请求");
        }, 500)
    },

    // 节流,在一秒内只会执行一次
    throttle_diy() {
        let now = new Date();
        if(now -this.lastTime > 2000) {
            console.log("节流操作,发送api请求")
            this.lastTime = now
        }
    }

  }
};
</script>

参考 https://blog.csdn.net/chang100111/article/details/120507415

封装

/**
 * @description 防抖函数
 * @param { Function } fun 函数
 * @param { Number } delay 间隔时间; 默认间隔1秒
 * @return { Function } 防抖处理后的函数
 */
export function debounce(fun, delay = 1000) {
    let time = null
    return function() {
        let self = this
        if(time) clearTimeout(time)
        time = setTimeout(() => {
            fun.apply(self, arguments)
        }, delay)
    }
}
/**
 * @description 节流函数
 * @param { Function } fun 函数
 * @param { Number } delay 间隔时间; 默认间隔1秒
 * @return { Function } 节流处理后的函数
 */
export function throttle(fun, delay = 1000) {
    let lastTime = new Date()
    return function() {
        let self = this
        let nowTime = new Date()
        if(nowTime - lastTime >= delay) {
            fun.apply(self, arguments)
            lastTime = new Date()
        }
    }
}

相关文章

网友评论

      本文标题:防抖节流

      本文链接:https://www.haomeiwen.com/subject/tkugoltx.html