AniUI Academy
hard+350 XPPractice

Model cancellation like AbortController

When a modal closes or a route changes, the work it started is no longer wanted. AbortController is how the platform expresses that: a controller holds the abort() method, and the passive signal is handed to whatever should stop. Building it yourself makes the contract concrete.

Implement two things. First, createCanceller() returns an object { signal, cancel }. signal.cancelled starts as false and signal.reason starts as null. Calling cancel(reason) sets cancelled to true and stores reason, defaulting to the string "Cancelled", and synchronously calls every listener registered with signal.onCancel(listener), passing the reason. Cancelling twice does nothing the second time: the first reason is kept and listeners are not called again. A listener registered after cancellation is called immediately with the stored reason. Second, delay(ms, signal) returns a promise that resolves with undefined after ms milliseconds, but rejects with new Error(signal.reason) as soon as the signal is cancelled, clearing its timer. If the signal is already cancelled when delay is called, it rejects straight away. signal may be omitted, in which case the delay simply resolves.

What it has to do

  • Start with cancelled false and reason null.
  • Default the cancel reason to the string Cancelled.
  • Call onCancel listeners synchronously, once, in registration order.
  • Call a listener registered after cancellation immediately.
  • Have delay reject with an Error carrying the reason, both when cancelled while waiting and when already cancelled.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.