Sequence NODE_157
Medium

Implement a Throttle Function

JavaScript
Technical Specification

Implement a throttle function that ensures a callback is called at most once in a given interval.

Input/Output Samples
Input:throttle(fn, 500)
Output:fn can execute at most every 500ms
Optimal Logic Path
function throttle(fn, delay) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= delay) {
      last = now;
      fn.apply(this, args);
    }
  };
}
Architectural Deep-Dive
We store the timestamp of the last call and only invoke the function again if enough time has passed.