VUE中使用防抖和节流

9 篇文章 0 订阅

目的:减少请求次数,节省资源
防抖:在事件触发n秒后执行函数,如果在n秒内再次出发,就重新计算
节流:在多次执行某一动作时,限制为每隔一段时间执行一次函数。
防抖:
连续的事件,只需触发一次:

eg:
高频率的点击
防止表单重复提交
输入框搜索。输完,再发送请求
鼠标的mousemove、mouseover

1,简单封装(不需要传参的情况,setTimeout就可以解决)

export const debounce = (fn,delay) => {
	let timer = null;
	if(timer){
		clearTimerout(timer)
	}
	timer = setTimerout(() => { fn() }, delay)
}

2,封装(需要传参的情况)

export const debounce = (fn,delay) => {
	let timer = null;
	return function () {
		clearTimerout(timer)
		let args = Array.prototype.slice.call(arguments)
		timer = setTimerout(() => { fn() }, delay)
	}
}

节流:
间隔一段时间执行一次:

eg:
scroll以及鼠标移动事件
1,封装(setTimeout就可以解决)

export const throttle = (fn,delay) => {
	let timer = null;
	return function () {
		let context = this;
		let args = Array.prototype.slice.call(arguments)
		if(timer){
			return
		}
		timer = setTimerout(() => { 
			fn.apply(context, args) 
			timer = null
		}, delay)
	}
}

2,封装(new Date()解决)

export const throttle = (fn,delay) => {
	let prev = 0;
	return function () {
		let now = new ;
		let context = this;
		let args = Array.prototype.slice.call(arguments)
		if(now - prev >=delay){
			fn.apply(context, args) 
			prev = now
		}
	}
}

另外(工具库):
Underscore.js 是一个实用的JavaScript工具库,提供了类似 Prototype 功能的编程支持,但没有对 JavaScript 内置的对象进行扩展。

import underscore from 'underscore';
underscore.debounce(this.test, 1000)

Lodash.js JavaScript 实用工具库。

import lodashfrom 'lodash';
lodash.debounce(this.test, 1000)
  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值