Question Prompt:
“Implement a debounce function in JavaScript. The function should take another function fn and a delay wait (in ms). When the returned function is repeatedly invoked, it should postpone the execution of fn until after wait milliseconds have elapsed since the last time it was invoked.”
Follow-up clarifications you might ask the candidate:
- Should the function run immediately on the first call (
leading) or only after the wait (trailing)? - Do we need a way to cancel or flush the debounced call?
- What real-world use cases can you think of? (e.g., search box input, resize, scroll events).