Overview
Implement throttle(fn, delay) — returns a throttled function that invokes fn at most once per delay ms. The first call fires immediately.
Constraints
- First invocation fires immediately
- Subsequent calls during cooldown are ignored
- Uses leading-edge throttling
Solution
Reveal solution
function throttle(fn, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
lastTime = now;
return fn.apply(this, args);
}
};
}throttle.js
Throttle
mediumcodingJavaScriptFunctions
Overview
Implement throttle(fn, delay) — returns a throttled function that invokes fn at most once per delay ms. The first call fires immediately.
Constraints
- First invocation fires immediately
- Subsequent calls during cooldown are ignored
- Uses leading-edge throttling
Solution
Reveal solution
function throttle(fn, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
lastTime = now;
return fn.apply(this, args);
}
};
}NameTopicDifficulty
103 of 103 problems