FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

useTimeout

15mins

Implement a utility useTimeout(callback, delay) that invokes a callback function after a specified delay.

Unlike using plain setTimeout, this utility should be reactive to changes in callback or delay values:

  • If the callback changes, the latest callback should be invoked when the timer fires.
  • If the delay changes, any pending timer should be canceled and a new one scheduled.
  • If delay is null, the timeout should be cleared and the callback never runs.

Your task: Implement useTimeout(callback, delay) so that:

  • It automatically cleans up when canceled.
  • It always calls the most recent callback.

Example

let loading = true; useTimeout(() => { loading = false; }, 1000); // Initially: loading = true // After 1000ms → loading = false

This mimics React’s useTimeout pattern but can be used in plain JavaScript too.

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests