Skip to content

Instantly share code, notes, and snippets.

@wyrfel
Last active November 12, 2023 19:23
Show Gist options
  • Save wyrfel/28c65228fcf527a56238bd9b7f860dd5 to your computer and use it in GitHub Desktop.
Save wyrfel/28c65228fcf527a56238bd9b7f860dd5 to your computer and use it in GitHub Desktop.
RxJS timer() replacement for values more than 24 days in the future
// compare https://github.com/ReactiveX/rxjs/issues/3015
import { concat, last, Observable, repeat, scan, SchedulerLike, take, timer } from 'rxjs';
import { map } from 'rxjs/operators';
const MAX_INT = 2147483647;
const getTimer = (time: number, scheduler: SchedulerLike | undefined): Observable<0> => {
if (time > MAX_INT) {
const n: number = Math.floor(time / MAX_INT);
const r: number = time % MAX_INT;
return concat(timer(MAX_INT, MAX_INT, scheduler).pipe(take(n)), timer(r, scheduler)).pipe(
last(),
map(() => 0)
);
}
return timer(time, scheduler);
};
const isInterval = (interval: SchedulerLike | number | undefined): interval is number => typeof interval === 'number';
export const longTimer = (
time: number | Date,
interval?: SchedulerLike | number,
scheduler?: SchedulerLike
): Observable<number> => {
if (time instanceof Date) {
time = time.getTime() - new Date().getTime();
}
if (!isInterval(interval)) {
return getTimer(time, interval);
}
return concat(
getTimer(time, scheduler),
getTimer(interval, scheduler).pipe(
repeat(),
scan((acc) => acc + 1, 0)
)
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment