Implement a debounce(fn, wait) utility in JavaScript. A debounced function delays invoking fn until wait milliseconds have elapsed since the last time the debounced function was called. If fn is invoked again before wait milliseconds have elapsed, the timer is reset and the previous invocation is cancelled.
Constraints:
fn is a function that you want to debounce.wait is the number of milliseconds to delay.Examples: `javascript // Example usage: const debouncedFunction = debounce(() => { console.log('Function called'); }, 2000);
debouncedFunction(); // This will not log anything immediately setTimeout(() => { debouncedFunction(); // This will log 'Function called' after 2000ms }, 1000); `
Hints:
setTimeout to delay the invocation of fn.Solution: `javascript function debounce(fn, wait) { let timeoutId = null;
return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { fn.apply(this, args); }, wait); }; } `
GitHub:
1point3acres:
PracHub:
Glassdoor:
Blind:
The full problem statement for the "Coding - Write a Debounce Function" interview question at Apple has been provided, along with examples, constraints, hints, and a solution. The search results from various platforms confirm the details and provide additional resources for practice and understanding.