防抖与节流

1.防抖Debounce

  • 指在某个事件频繁触发时,延迟一定时间后再执行回调函数。如果在延迟时间内又触发了同样的事件,那么会重新计时。
  • 多次触发,只执行最后一次

1.1应用场景

  • 搜索框实时搜索:当用户输入时,防抖可以用于延迟发送请求,避免频繁请求后端接口。
  • 表单输入验证:使用防抖函数可以延迟触发验证操作,只在用户输入完毕一段时间后进行验证,避免频繁的验证操作。
  • 窗口大小调整:当窗口大小调整时,防抖可以用于调整事件触发的频率,避免频繁操作导致页面抖动。

1.2 实现防抖函数

  • 思路:延迟函数执行并重新计时以确保在一段时间内只执行一次函数
<div><input type="text" id="debounce"></div>

const debounceDom = document.getElementById('debounce')
// 使用防抖函数,确保在连续触发 keyup 事件时只触发一次 ajax 函数
debounceDom.addEventListener('keyup', debounce(ajax, 500))

// 模拟一个 ajax 请求
function ajax() {
	console.log('这是一个请求');
}

// 实现防抖的函数
function debounce(fn, time) {
    let timer = null
    return function () {
    	if (timer) { //说明上次定时器还没有执行完 清除上次定时器
    		clearTimeout(timer)
    	}
    	timer = setTimeout (() => {
    		// 使用apply将函数fn的执行上下文设置为当前函数的执行上下文,并传入当前函数的参数
    		fn.apply(this, arguments) 
    	}, time)
	}
}

2.节流Throttle

  • 指规定一个单位时间(延迟 delay 时间),只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。

  • 规定时间内,只触发一次

2.1 应用场景

  • 页面滚动加载
  • 频繁点击按钮
  • 鼠标移动
  • 键盘按键
  • 动画场景:避免短时间内多次触发动画引起性能问题
  • 拖拽场景: 在某些场景下,频繁触发位置变动会造成性能问题

2.2 实现节流函数

  • Date.now()获取时间来判断是否在规定时间内
function throttle (fn, delay) {
	let prevTime = Date.now();
	return function(){
		if(Date.now() - prevTime > delay){
			fn.apply(this, arguments)
			prevTime = Date.now()
		}
	}
}
  • 设置一个flag来标志
function throttle (fn, delay) {
	let flag = true
	return function () {
		if (flag) {
			setTimeout(() => {
				fn.apply(this, arguments)
				flag = true
			}, delay)
		}
		flag = false
	}
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值