防抖(debounce)与节流(throttle)

防抖

原理:在事件触发n秒后,执行方法。如果在n秒内被重新触发,则重新开始计时。结果就是将频繁的事件合并成一次。
例如:电梯每5秒会开始运作。如果在5秒内,有人进来,则重新计时,直到超过5秒。
场景:input输入数据请求服务
实现:

function debounce(fn,wait) {
    let timer; // 计时器
    return function () {
        // 重置计时器
        clearTimeout(timer); 
        timer= setTimeout(() => {
            fn.apply(this, arguments);
        }, wait);
    };
}

节流

原理:事件在触发n秒内,执行方法。如果n秒内再次触发,不重置。结果是将一定时间内的重复事件合并成一次。
场景:上拉加载数据
实现:
1. 定时器

function throttle(fn, wait) {
    var timer;
    return function() {
        if (!timer) {
            timer = setTimeout(function(){
                timer = null;
                fn.apply(this, arguments)
            }, wait)
        }
    }
}

2. 时间戳

function throttle(fn, wait) {
    var previous = 0;
    return function () {
        var now = Date.now();
        if (now - previous > wait) {
            fn.apply(this, arguments);
            previous = now;
        }
    }
}

小结

防抖的思想是在一系列高频操作结束后,等待一定时间后执行一次。节流是在一定时间内,只执行一次。

  • 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、付费专栏及课程。

余额充值