防抖和节流的简易封装和使用

70 阅读1分钟

防抖

export function debounce(fn, wait = 500) {
	let timer
	return function() {
		let context = this
		let arg = arguments
		if (timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			fn.apply(context, arg)
		}, wait)
	}
}

使用

//鼠标点击事件
useDebounce:debounce(function() {
    //逻辑
})

节流(时间差)

export function throttle(fn, wait=500) {
	let lastTime = 0
	return function() {
		let context = this
		let arg = arguments
		let nowTime = +new Date().getTime()
		if (nowTime - lastTime > wait) {
			fn.apply(context, arg)
			lastTime = nowTime
			console.log(lastTime,2);
		}
	}

}

使用

let _=this
let throttled = throttle(_.myFunction, 5000); // 5000ms后才能再次执行
// 在某些事件中调用throttled
window.addEventListener('resize', throttled);
// 使用示例
function myFunction() {
    console.log("触发!");
}