防抖和节流

1.防抖

防抖是一种在一定时间内只执行最后一次操作的技术,可以有效防止按钮被频繁点击。

应用场景:

适用于用户输入、搜索框输入联想、窗口大小调整、搜索按钮等频繁触发的事件,

确保只有在用户停止输入或事件静止一段时间后才会执行相关操作。

vue2+js

<template>
<button @click="onClick">点击我</button>
</template>
 
<script>
export default {
  methods: {
//在按钮上绑定防抖处理函数
    function debounce(func, delay) {
//func是点击按钮后要执行的操作,delay是规定延迟的时间
      let timer;
      return function () {
//每次按钮被点击时,会先清除之前的定时器,然后设置一个新的定时器
           clearTimeout(timer);
           timer = setTimeout(() => {
//在延迟结束时间后,调用func
                func.apply(this, arguments);
//this是事件处理函数内部的上下文,arguments包含事件处理函数的所有参数
                }, delay);
  };
}
 
//已经经过防抖处理的点击函数
const onClick = debounce(function () {
  // 在这里执行按钮点击后的操作
  console.log('Button clicked!');
}, 1000); // 1秒内只会执行一次
 
 
//const onClick = debounce(api, 1000); 
//funcitton api(){console.log('...')};
 
//当按钮被点击后,如果在指定的延迟时间内再次点击,之前的定时器会被清除,并重新设置一个新的定时器。这样只有在最后一次点击经过了指定延迟的时间,才会执行实际操作
 
//apply 是 JavaScript 中的一个函数方法,它允许你在调用函数时设置函数体内 this 的值,并以数组(或类数组对象)的形式传递参数。
};
</script>

vue3+ts

<template>
  <button @click="onClick">点击我</button>
</template>
 
<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
 
const debounce = (func: Function, delay: number) => {
  let timer: number | null = null;
  return (...args: any[]) => {
//将所有传递给debounce函数的参数收集到args数组中
    clearTimeout(timer as number);
    timer = setTimeout(() => {
      func(...args);
    }, delay);
  };
};
 
const onClick = debounce(async () => {
  try {
    // 发起接口请求
    const response = await axios.get('https://api.example.com/data');    
    // 处理接口返回的数据
    console.log('API Response:', response.data);
  } catch (error) {
    // 处理错误
    console.error('Error calling API:', error);
  }
}, 1000); // 1秒内只会执行一次
</script>
2.节流

节流是一种在一定时间内只执行一次操作的技术,主要是按照一定时间间隔执行。

应用场景:

适用于需要在一定时间间隔内均匀执行函数的场景,如滚动事件、鼠标移动等

vue2+js

<template>
<button @click="onClick">点击我</button>
</template>
 
<script>
export default {
  methods: {
    // 节流函数(该函数返回一个新函数,用于包装其他函数,以限制他们的执行频率)
    function throttle(func, delay) {
    //用于标志是否允许执行按钮点击之后的操作
      let throttled = false;
 
      return function () {
        if (!throttled) {
          // 如果未执行过,则执行函数
          func.apply(this, arguments);
          throttled = true;
          // 设置一个延迟后重置节流状态,允许再次触发执行
          setTimeout(() => {
            throttled = false;
          }, delay);
        }
      };
    },
 
    // 已经经过节流处理的点击函数
    onClick: throttle(function () {
      // 在这里执行按钮点击后的操作
      console.log('Button clicked!');
    }, 1000), // 每隔1秒执行一次
 
    // 当按钮被点击后,在间隔时间内再次点击不会立即触发执行函数,而是等待间隔时间后执行。间隔时间内的点击会被忽略。
  }
};
</script>
//当点击按钮时,throttle函数会检查throttled的值;如果throttled为false,则执行相应操作,并将throttled设置为true,表示在一段时间内不允许再次执行。随后,通过使用 setTimeout,在一定延迟之后,throttled 被重置为 false,从而允许下一次点击触发相应的操作。

vue3+ts

<template>
  <button @click="onClick">点击我</button>
</template>
 
<script lang="ts">
import { defineComponent } from 'vue';
 
export default defineComponent({
  methods: {
    // 节流函数
    throttle(func: Function, delay: number) {
      let throttled = false;
 
      return function (this: any, ...args: any[]) {
        if (!throttled) {
          // 如果未执行过,则执行函数
          func.apply(this, args);
          throttled = true;
          // 设置一个延迟后重置节流状态,允许再次触发执行
          setTimeout(() => {
            throttled = false;
          }, delay);
        }
      };
    },
  },
 
  setup() {
    // 在setup中使用响应式数据和方法
    const onClick = this.throttle(function (this: any) {
      // 在这里执行按钮点击后的操作
      console.log('Button clicked!');
    }, 1000);
 
    return {
      onClick,
    };
  },
});
</script>

ok🦌

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值