Skip to content

Instantly share code, notes, and snippets.

@heyMP
Last active November 12, 2022 23:40
Show Gist options
  • Save heyMP/c80fbe3a5cf8b8cfe8ce3e6697cda2c0 to your computer and use it in GitHub Desktop.
Save heyMP/c80fbe3a5cf8b8cfe8ce3e6697cda2c0 to your computer and use it in GitHub Desktop.
A promised based overservable pattern.
// @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