防抖与节流

问题:

有时候多次点击按钮会多次触发响应时间,尤其是向后台请求数据时,多次请求更容易造成卡顿。

解决:

1. 防抖:规定时间内,以最新的触发事件为准,取消之前的事件,执行最新的事件

2. 节流:规定时间内,以第一次触发为准,之后的触发在第一次操作还存在的情况下,忽略事件触发。

具体实现:

// 防抖:
    // 规定时间内,每次触发都会取消掉之前的定时器,创建新的定时器,若规定时间内未再次触发,则规定时间之后执行函数    
// 第一参数是触发的函数,第二参数是延时时间
    function debounce(fn, wait) {
        let timeout = null;    
        return function() {        
            if(timeout !== null)   clearTimeout(timeout);        
            timeout = setTimeout(fn, wait);    
        }
    }

window.addEventListener('click', debounce(handle, 3000));

// 节流:
    // 规定时间内只执行一次,如果存在已创建的定时器就不会再创建新的定时器
// 第一参数是触发的函数,第二参数是延时时间
// 定时器版
    function throttle(func, wait) {
      let timeout;
      return function() {
        if (!timeout) {
          timeout = setTimeout(()=> {
            func();
            timeout = null;
          }, wait)
        }
      }
    }

// 时间戳版:
function throttle(func, wait) {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}

function handle() {            
  console.log("你好");        
}

window.addEventListener('click', throttle(handle, 3000));

 

 

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

余额充值