Skip to content

Instantly share code, notes, and snippets.

@jakewtaylor
Last active July 30, 2019 09:42
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 jakewtaylor/a98978d43af6388c24567b9d86d90355 to your computer and use it in GitHub Desktop.
Save jakewtaylor/a98978d43af6388c24567b9d86d90355 to your computer and use it in GitHub Desktop.
const delay = (ms, token = null) => new Promise((resolve, reject) => {
const cancelled = () => reject({ cancelled: true });
if (token && token.cancelled) {
return cancelled();
}
const timeout = setTimeout(() => {
if (!token || !token.cancelled) {
resolve();
} else {
cancelled();
}
}, ms);
if (token) {
token.onCancel = () => {
clearTimeout(timeout);
cancelled();
};
}
});
class CancelToken {
cancelled = false;
cancel () {
this.cancelled = true;
this.onCancel();
}
onCancel () {
//
}
}
// Usage
const token = new CancelToken();
delay(2000, token)
.then(() => {
console.log('2 seconds passed!');
})
.catch(({ cancelled }) => {
if (cancelled) {
console.log('cancelled!');
}
});
if (Math.random() < 0.5) {
token.can
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment