防抖函数

26 阅读1分钟

应用场景:在基于搜索操作时,延时刷新list

export const _debounce = (fn, delay = 500, ctx) => {
	let timeoutVal
	const cacrryFun = (...args) => {
		timeoutVal && clearTimeout(timeoutVal)
		timeoutVal = setTimeout(() => {
			fn.apply(ctx, args)
		}, delay)
	}
	return cacrryFun
}

在lodash的js库中,也有类似实现

const cacrryFun = () => {
    _.debounce(() => {
        // to do something
    }, 250)
}