节流函数、防抖函数(前端)

本文介绍了JavaScript中的节流和防抖函数,它们用于优化事件处理,防止在短时间内频繁触发同一事件。节流函数允许在设定的时间间隔内只执行一次事件处理,而防抖函数则确保在最后一次操作后的一段延迟时间内执行。提供了详细的代码实现和使用示例,帮助开发者理解并应用于实际项目中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

节流函数

/**
 * @method 节流函数(500ms内只能点击一次,点击后立即触发,重读点击无效,必须等3s只后才能点击第二次)
 * @param {Function} {handler} 事件处理函数
 * @param {Number} {delay} 恢复点击的毫秒数
 */
export const throttle = (handler, delay = 500) => {
	let last, deferTimer
	return function (...args) {
		let that = this;
		let now = +new Date();
		if(last && now < last + delay) {
			deferTimer && clearTimeout(deferTimer)
			deferTimer = setTimeout(() => {
				last = now
				handler.apply(that, args)
			}, delay)
		} else {
			last = now
			handler.apply(that, args)
		}
	}
} 

防抖函数

/**
 * @method 防抖函数(500ms只后出结果,重复点击无效,如果重复点击了,重新计算3s时间,从点击的时刻算起,必须等待3s时间触发事件)
 * @param {Function} {handler} 事件处理函数
 * @param {Number} {delay} 恢复点击的毫秒数
 */
 export const debounce = (handler, delay = 500) => {
	let timeout
	return function (...args) {
		let that = this
		timeout && clearTomeout(timeout)
		timtout = setTimeout(() => {
			handler.apply(that, args)
		}, delay)
	}
 }

使用案例如下:

<template>
  <div>
    <button @click="IsButton"></button>
  </div>
</template>

<script>
//封装方法调用
const throttle = (handler, delay = 500) => {
  let last, deferTimer;
  return function (...args) {
    let that = this;
    let now = +new Date();
    if (last && now < last + delay) {
      deferTimer && clearTimeout(deferTimer);
      deferTimer = setTimeout(() => {
        last = now;
        handler.apply(that, args);
      }, delay);
    } else {
      last = now;
      handler.apply(that, args);
    }
  };
};
export default {
  data() {
    return {};
  },
  methods: {
    isButton: throttle(function (val) {
      //val 点击事件的参数
      //这里写入点击事件的逻辑
      //3000ms时间
      
    }, 3000),
  },
};
</script>

<style></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值