2627. Debounce
In this challenge, you must implement a debounced version of a function. A debounced function delays the execution of the original function until a given time in milliseconds has passed since the last time it was called.
π Problem Statement
Given a function fn and a delay t in milliseconds, return a debounced version of that function. When the debounced function is called, wait for t milliseconds before calling fn. If itβs called again during the delay period, cancel the previous call and restart the timer.
The debounced function must preserve the arguments from the most recent call.
π‘ Example
Scenario: t = 50ms
// Called at: 30ms, 60ms, 100ms
// 30ms call β cancelled
// 60ms call β cancelled
// 100ms call β runs at 150ms
Scenario: t = 35ms
// Called at: 30ms, 60ms, 100ms
// 30ms call β cancelled
// 60ms call β runs at 95ms
// 100ms call β runs at 135ms
π§ Explanation
You use setTimeout to delay execution, and clearTimeout to cancel any previously scheduled execution when a new call happens. This ensures the function is only called once the delay passes without interruption.
This technique is commonly used for performance optimization in web apps β for example, delaying API calls while a user types in a search box.
β Your Solution
/**
* @param {Function} fn
* @param {number} t
* @return {Function}
*/
var debounce = function(fn, t) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn(...args);
}, t);
};
};