Skip to content

Instantly share code, notes, and snippets.

@juliandavidmr
Created December 20, 2019 19:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juliandavidmr/8da3e0e4d2234ca56f95b9d038465487 to your computer and use it in GitHub Desktop.
Save juliandavidmr/8da3e0e4d2234ca56f95b9d038465487 to your computer and use it in GitHub Desktop.
Counterdown + RxJS
import { Observable, timer } from "rxjs";
import { map, takeWhile, take } from "rxjs/operators";
export function countdown(minutes: number, delay: number = 0) {
return new Observable<{ display: string; minutes: number; seconds: number, finished: boolean }>(
subscriber => {
timer(delay, 1000)
.pipe(take(minutes * 60))
.pipe(map(v => minutes * 60 - 1 - v))
.pipe(takeWhile(x => x >= 0 && !subscriber.closed))
.subscribe(count => { // countdown => seconds
const m = Math.floor(count / 60);
const s = count - m * 60;
subscriber.next({
display: `${('0' + m.toString()).slice(-2)}:${('0' + s.toString()).slice(-2)}`,
minutes: m,
seconds: s,
finished: m === 0 && s === 0
});
console.log('counter', count)
if (s <= 0 && minutes <= 0) {
subscriber.complete();
}
});
}
);
}
/**
Output:
{
"display": "00:53",
"minutes": 0,
"seconds": 53,
"finished": false
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment