js 防抖函数、节流函数

/** 节流函数 */
export function throttle(func, wait = 100) {
	let isDoing = false
	return function (...rest) {
		if (isDoing) return
		isDoing = true
		
		setTimeout(() => {
		    func(...rest)
			isDoing = false
		}, wait)
	}
}

/** 防抖函数 */
export function debounce(func, wait = 100) {
	let timer = 0
	return function (...rest) {
		clearTimeout(timer)
		timer = setTimeout(func, wait, ...rest)
	}
}
//测试
function throttle(func, wait = 100) {
	let isDoing = false
	return function (...rest) {
		if (isDoing) return
		isDoing = true
		setTimeout(() => {
			func(...rest)
			isDoing = false
		}, wait)
	}
}

function debounce(func, wait = 100) {
	let timer = 0
	return function (...rest) {
		clearTimeout(timer)
		timer = setTimeout(func, wait, ...rest)
	}
}

const normalFn = (e) => {
	console.log('normalFn', e)
}

const throttleFn = throttle((e) => {
	console.warn('throttleFn', e)
}, 100)

const debounceFn = debounce((e) => {
	console.error('debounceFn', e)
}, 200)

window.addEventListener('resize', (e) => {
	normalFn('params ' + Date.now())
	throttleFn('params ' + Date.now())
	debounceFn('params ' + Date.now())
})

效果图
js 防抖函数、节流函数_第1张图片

你可能感兴趣的:(javascript,开发语言,ecmascript)