Start learning free

LESSON 139 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Throttle in JavaScript

Practice

Some events fire very often: while a visitor scrolls, the page can get a scroll event every few milliseconds. Doing heavy work on each one is wasteful. A throttled function runs at most once per ms milliseconds: the first call runs at once and starts a wait.

Calls that come during the wait don't run then. Only the last one is kept, and when the wait ends, fn runs once more with its arguments: the trailing call. That run starts a new wait. If nothing was kept, the wait just ends, and the next call runs at once again.

You would use it like this, on another event:

const onMove = throttle(showPosition, 100);
window.addEventListener("mousemove", onMove);

The check calls your throttled functions on its own clock and prints each call and each time fn ran. For three quick clicks with click = throttle(fn, 1000) it must print:

0 ms: click("first")
0 ms: fn("first") runs
100 ms: click("second")
200 ms: click("third")
1000 ms: fn("third") runs
fn ran 2 times

Your task: make throttle(fn, ms) return a new function, throttled. It runs fn at once when no wait is running, keeps the arguments of the last call made during a wait, and runs fn with them when the wait ends.


Assignment
Follow the Coding Tutorial to write throttle with two inner functions: throttled, which runs or keeps each call, and endWait, which ends the wait and makes the trailing call.


Hint
waiting and lastArgs live inside throttle, so each throttled function keeps its own wait. For the trailing call, call throttled, not fn, so it starts a new wait, and then clear lastArgs.


STEP 1 OF 12
    Ctrl + Enter to check

    Fe Throttle in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free