Last active
July 30, 2019 09:42
-
-
Save jakewtaylor/a98978d43af6388c24567b9d86d90355 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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