← JavaScript Coding

Cancellable Timeout

easytimersclosures
Asked at
Amazon
Google
Meta
PayPal
Uber
Amazon, Google, Meta, PayPal, Uber

Problem statement

Implement setCancellableTimeout. It should behave like setTimeout, but instead of returning a timer id, it returns a function that cancels the pending callback.

Signature

setCancellableTimeout(callback);
setCancellableTimeout(callback, delay);
setCancellableTimeout(callback, delay, param1);
setCancellableTimeout(callback, delay, param1, param2);

Example

let i = 0;
const cancel = setCancellableTimeout(() => {
  i++;
}, 100);

cancel();
// i is still 0 after 100ms

Requirements & constraints

  • →Match the `setTimeout` argument shape.
  • →Return a cancel function.
  • →Do not execute the callback after cancellation.

How to approach Cancellable Timeout

The strategy an interviewer expects you to reach for.

UI code schedules work it may cancel — route changes, unmounts, newer keystrokes. A cancellable timeout returns that cancel handle. Naive move Call setTimeout and forget to expose clearTimeout, or clear the wrong id. Where it breaks Without cancel, callbacks fire after unmount and set state on dead components. Extra args must still forward into the timer callback. The fix Capture the timer id in a closure. Return a cancel function that clears it. Forward ...args to setTimeout. Remember: Always return a cancel; always clearTimeout the same id you created. Say this in the interview: I'd wrap setTimeout, keep the id in a closure, forward args, and return a cancel function that clearTimeouts that id.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Runnable editor with the hidden test suite
  • Progressive hints that unlock as you get stuck
  • Senior-level reference solution with a line-by-line walkthrough
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingEasy

City Fetcher API

JS CodingHard

promise.all( )

JS CodingHard

promise.allSettled( )

JS CodingHard

promise.any( )

JS CodingHard

promise.race( )

JS CodingEasy

promise.reject()

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Amazon interview
  • Google interview
  • Meta interview
  • PayPal interview
  • Uber interview