Last active
November 12, 2022 23:40
-
-
Save heyMP/c80fbe3a5cf8b8cfe8ce3e6697cda2c0 to your computer and use it in GitHub Desktop.
A promised based overservable pattern.
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
// @ts-check | |
/** | |
* Countdown timer as an observable. | |
* | |
* @param {number} timeout - Specified time to resolve the countdown specified in seconds. | |
* @param {?(number) => void} callback - Callback that updates on countdown change. | |
* @returns {{ cancel?: (string) => void, promise: Promise<void>}} | |
*/ | |
export function countdown(timeout, callback = null) { | |
const ret = {}; | |
const signal = new Promise((res, rej) => { | |
ret.cancel = (err) => { | |
rej(new Error(err)); | |
} | |
}); | |
ret.promise = new Promise((res, rej) => { | |
let index = timeout; | |
const interval = setInterval(() => { | |
index-- | |
if (!!callback) { | |
callback(index); | |
} | |
if (index <= 0) { | |
res(); | |
clearInterval(interval); | |
} | |
}, 1000); | |
signal.catch(err => { | |
rej(err); | |
clearInterval(interval); | |
}) | |
}); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment