Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Created June 30, 2021 19:01
Show Gist options
  • Save gaurangrshah/4dc0b5bbb91f3c7a708df7b7039936a1 to your computer and use it in GitHub Desktop.
Save gaurangrshah/4dc0b5bbb91f3c7a708df7b7039936a1 to your computer and use it in GitHub Desktop.
const delay = (delay, value) => {
let timeout;
let _reject = null;
const promise = new Promise((resolve, reject) => {
_reject= reject;
timeout = setTimeout(resolve, delay, value);
});
return {
promise,
cancel() {
if(timeout) {
clearTimeout(timeout);
timeoout = null;
_reject();
_reject = null;
}
}
};
};
/* usage
const delayed = delay(5000, value);
delayed.promise.then((value) => console.log(value)).catch(() => console.error("Rejected"));
delayed.cancel();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment