Scriptdrill

Level 5: Async and functions Exercise 40 of 45 Pro

Debounce

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return a debounced version of `fn`: calling it schedules `fn` to run `wait` ms later with the latest arguments, and every new call before then restarts the wait. So a burst of calls runs `fn` once, after the burst goes quiet. Tests run on a fake clock: `setTimeout`, `clearTimeout` and `Date.now` are simulated, so waits are instant and exact.

What this exercise teaches

Clearing the pending timer on every call is what restarts the wait; only the timer from the last call survives long enough to fire, and it carries that call's arguments.

A hint if you get stuck

Keep the timer id in a variable outside the returned function. On every call, `clearTimeout` the old timer and set a new one that calls `fn(...args)`.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Async and functions