Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active February 12, 2021 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/8dbd213192862b8671be58879e1cda86 to your computer and use it in GitHub Desktop.
Save ccnokes/8dbd213192862b8671be58879e1cda86 to your computer and use it in GitHub Desktop.
Use AbortController to implement custom async task cancelling logic. Expounded upon here: https://cameronnokes.com/blog/cancelling-async-tasks-with-abortcontroller/
function wait(ms, opts = {}) {
return new Promise((resolve, reject) => {
let timerId = setTimeout(resolve, ms);
if (opts.signal) {
// implement aborting logic for our async operation
opts.signal.addEventListener('abort', event => {
clearTimeout(timerId);
reject(event);
});
}
});
}
let abortController = new AbortController();
wait(100, { signal: abortController.signal })
.then(() => console.log('wait complete'))
// catch the aborted promise rejection in here
.catch(console.error);
abortController.abort();
// => Error: Event { type: 'abort', ... }
@Gjum
Copy link

Gjum commented Feb 12, 2021

You don't clean up the event handler when wait returns normally (not aborted) which is a memory leak.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment