Fix the Throttle Function
HardChallenge 13 of 20
Fix the Throttle Function
HardThis throttle utility function is supposed to limit how often a function can be called to once per specified time period, but it's not working correctly. Fix the implementation.
Challenge 13 of 20
80 XP
Community Solutions
Utility FunctionsPerformanceTimingJavaScript
Exit ChallengeTest Cases
0/1 passingTest Case #1
Input: Call throttledScroll multiple times rapidly
Expected: Should execute at most once per second
Run tests to see results
solution.js
1
<span class="token keyword">function</span> throttle(func, limit) {
<span class="token keyword">let</span> inThrottle;
<span class="token keyword">return</span> <span class="token keyword">function</span>() {
<span class="token keyword">const</span> args = arguments;
<span class="token keyword">const</span> context = <span class="token keyword">this</span>;
<span class="token keyword">if</span> (!inThrottle) {
func.apply(context, args);
inThrottle = <span class="token boolean">true</span>;
setTimeout(() => inThrottle = <span class="token boolean">false</span>, limit);
}
};
}
<span <span class="token keyword">class</span>=<span <span class="token keyword">class</span>="token string">"token comment"</span>>// Example usage:</span>
<span class="token keyword">const</span> throttledScroll = throttle(<span class="token keyword">function</span>() {
console.log(<span <span class="token keyword">class</span>="token number">039</span>;Scroll event throttled<span <span class="token keyword">class</span>="token number">039</span>;);
}, <span <span class="token keyword">class</span>="token number">1000</span>);
<span <span class="token keyword">class</span>=<span <span class="token keyword">class</span>="token string">"token comment"</span>>// This should log at most once per second</span>
window.addEventListener(<span <span class="token keyword">class</span>="token number">039</span>;scroll<span <span class="token keyword">class</span>="token number">039</span>;, throttledScroll);Console
Run your code to see output here