Created
December 20, 2019 19:17
-
-
Save juliandavidmr/8da3e0e4d2234ca56f95b9d038465487 to your computer and use it in GitHub Desktop.
Counterdown + RxJS
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
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