难得在掘金这么个技术氛围浓厚的地方遇到肚子没点墨水的爷新,虽说签名是给这些又菜又拉又爱装的人看的,可惜某些人就是自大张嘴就来啊,既然爷新要爷爷来肛,求之不得,故出此文以打脸之。以此教此类只会教条主义,看点缺斤短两的面试文就自认会了会了的爷新怎么写一个具备immediate的较完善的debounce。
1. d.ts文件
.d.ts文件以抛砖引玉,梳理思路,整理输入输出
export function debounce<F extends (...args: any[]) => any>( fn: F, wait?: number, immediate?: boolean): F & { cancel(): void };
2. 源码
export default function (fn, wait = 250, immediate) { let timeout function debounced (/* ...args */) { const args = arguments const later = () => { timeout = void 0 if (immediate !== true) { fn.apply(this, args) } } clearTimeout(timeout) if (immediate === true && timeout === void 0) { fn.apply(this, args) } timeout = setTimeout(later, wait) } debounced.cancel = () => { clearTimeout(timeout) } return debounced}