Menu

1 / 2

Cancelling timers with AbortController: seven cases including cleanup

DEV Community: node·hiro@·2 days ago
#85AzRQXd
#devtonodejs#devto#dev#signal#abort
Reading 0:00
15s threshold

AbortController is not limited to fetch. Calling abort() does not stop an arbitrary Promise, though. The operation must accept the signal and implement both stopping its wait and rejecting its Promise.

A small timer function was tested with cancellation before it started, while it was waiting, and after completion. The check covered not only rejection, but also whether abort listeners remained after the operation ended.

Implement a delay that handles cancellation

Save this function as cancellable-delay.mjs . It is an implementation for this experiment, not code already integrated into an existing application.

export function delay ( ms , signal ) { return new Promise (( resolve , reject ) => { if ( signal . aborted ) { reject ( signal . reason ); return ; } const cleanup = () => signal . removeEventListener ( ' abort ' , onAbort ); const onAbort = () => { clearTimeout ( timer ); cleanup (); reject ( signal .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.