VUE中使用防抖和节流

目的:减少请求次数,节省资源
防抖:在事件触发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)

你可能感兴趣的:(vue,js,vue.js,js)