Created
June 30, 2021 19:01
-
-
Save gaurangrshah/4dc0b5bbb91f3c7a708df7b7039936a1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 = (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