防抖(debounce)与节流(throttle)

应用

  • 防抖与节流函数,可以控制事件被触发的频率,主要应用于以下场景
    • 输入框,需要监测键盘按下抬起事件 – onkeyup、onkeydown
    • 浏览器窗口的尺寸变化事件 – onresize
    • 溢出滚动事件 – onscroll
    • 按钮点击事件,防止重复提交 – onclick

区别

防抖(debounce)

  • 函数在触发后,规定在时间范围内只执行一次。如果再次触发了函数,则重新计时,取消之前的调用。即无论被触发多少次,只取最后一次。

节流(throttle)

  • 函数在时间范围内,只执行一次。在此时间范围内,判断是否有过调用,如果已经调用过,则禁止再触次发执行函数。

实现

防抖(debounce)

<template>
    <div class="hello">
        <input type="text" v-model="myText" @keyup="keyupFunc" />
    </div>
</template>

<script>
export default {
    name: "HelloWorld",
    data() {
        return {
            myText: "", // 输入框绑定的值
            timmer: null, // 定义全局变量
        };
    },
    methods: {
    	debounce(func, delay) {
            return (() => {
                if (this.timmer) {
                    // 如果已经存在,说明之前执行过了,这里要清除,重新开始
                    console.log("%c清理定时器的操作~", "color: blue;");
                    clearTimeout(this.timmer);
                }
                this.timmer = setTimeout(func, delay);
            })();
        },
        // input 输入框,键盘抬起事件触发
        keyupFunc() {
            let time = new Date().getTime();
            console.log(
                "%c不加入防抖-触发结果:" + this.myText + ",时间戳:" + time,
                "color: red;"
            );
            this.debounce(() => {
                console.log(
                    "%c加入防抖-触发结果:" + this.myText + ",时间戳:" + time,
                    "color: green;"
                );
                this.timmer = null;
            }, 2000);
        },
    },
};
</script>

在这里插入图片描述

  • 输入框中频繁连续输入数字 1,不加防抖的 console 每次都会被执行,并且从第二次开始,有清理定时器的操作。
  • 在 2 秒内不再操作时,打印绿色字体,此时才被认为事件触发。
  • 实际应用
    • 监听 input 的键盘抬起事件(如上例),在抬起 2 秒后未再次触发函数,则认定用户不再输入,此时做输入内容的校验、远程搜索等功能。
    • 浏览器大小的变化,onresize 事件,在尺寸变化被触发后,2 秒内不再被触发,则认为用户不再拖动尺寸大小,此时做尺寸适配、重新加载数据等功能。

节流(throttle)

<template>
    <div class="helloBox" @scroll="scrollFunc" ref="helloBox">
        <div class="helloLong"></div>
    </div>
</template>

<script>
export default {
    name: "HelloWorld",
    data() {
        return {
            myText: "",
            timmer: null,
        };
    },
    methods: {
        throttle(func, delay) {
            return (() => {
                if (this.timmer) {
                    // 如果已经存在,说明之前执行过了,这里停止方法
                    console.log(
                        "%c已经执行过了,停止方法",
                        "color: blue;",
                        this.timmer
                    );
                    return;
                } else {
                    this.timmer = setTimeout(func, delay);
                }
            })();
        },
        // 监听滚动事件
        scrollFunc() {
            let height = this.$refs.helloBox.scrollTop;
            let time = new Date().getTime();
            console.log(
                "%c不加入节流-触发结果:卷曲出去的距离:" +
                    height +
                    ",时间戳:" +
                    time,
                "color: red;"
            );
            this.throttle(() => {
                console.log(
                    "%c加入节流-触发结果:卷曲出去的距离:" +
                        height +
                        ",时间戳:" +
                        time,
                    "color: green;"
                );
                this.timmer = null;
            }, 200);
        },
    },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.helloBox {
    height: 100%;
    overflow-y: scroll;
}
.helloLong {
    height: 500%;
}
</style>

在这里插入图片描述

  • 向下滚动时,每隔一段时间,触发一次节流事件。
  • 除了定时器,节流函数还可用时间戳控制事件的触发。
  • 实际应用
    • 需要监听页面滚动事件时(如上例),防止监听事件频繁触发。
    • 表单提交事件,防止用户重复提交,可规定在一定时间内,提交时间只能被触发一次。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue中,有一些常用的防抖节流插件可以方便地实现防抖节流的功能。以下是两个常用的插件: 1. Lodash(防抖节流) Lodash是一个JavaScript实用工具库,它提供了许多常用的函数和方法,包括防抖节流函数。使用Lodash的`debounce`和`throttle`函数可以很方便地实现防抖节流。 安装Lodash: ```bash npm install lodash ``` 使用示例: ```javascript import { debounce, throttle } from 'lodash'; // 防抖示例 const debouncedFunc = debounce(() => { console.log('执行操作'); }, 500); // 节流示例 const throttledFunc = throttle(() => { console.log('执行操作'); }, 200); ``` 2. Vue-lodash(防抖节流) Vue-lodash是一个专门为Vue开发的Lodash插件,它提供了Vue指令的方式来使用Lodash的方法,包括防抖节流。 安装Vue-lodash: ```bash npm install vue-lodash ``` 在Vue项目中使用Vue-lodash示例: ```javascript import Vue from 'vue'; import VueLodash from 'vue-lodash'; import { debounce, throttle } from 'lodash'; Vue.use(VueLodash, { lodash: { debounce, throttle } }); ``` 在Vue组件中使用防抖节流: ```html <template> <div> <button v-debounce:click="debouncedFunc">点击按钮(防抖)</button> <button v-throttle:click="throttledFunc">点击按钮(节流)</button> </div> </template> <script> export default { methods: { debouncedFunc() { console.log('执行操作'); }, throttledFunc() { console.log('执行操作'); }, }, }; </script> ``` 以上是两个常用的Vue插件,可以方便地在Vue项目中使用防抖节流功能。根据具体需求选择合适的插件来使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值