Problem, as an interviewer would state it:
"Implement debounce(fn, wait, options) — delay calling fn until wait ms have passed with no new calls. Support a leading option (fire on the first call of a burst), a trailing option (fire on the last), and .cancel()/.flush() methods on the returned function."
Examples:
const d = debounce(save, 300);
d(); d(); d(); // rapid calls -> save() runs once, 300ms after the LAST call
d.cancel(); // pending call is discarded
Clarifying questions expected:
- If both
leadingandtrailingare true, should the function fire TWICE for a single burst (once immediately, once at the end)? - Does
this/arguments binding need to be preserved for the eventually-invoked call? - What should
.flush()do if nothing is currently pending?
Code / implementation expected: Yes — real, direct proof of all 4 real modes (trailing-only, leading-only, cancel, flush) plus the leading+trailing combination.