Last active
June 4, 2020 19:18
-
-
Save jacksteamdev/49bdac75eccd1d9de5f230986a70a233 to your computer and use it in GitHub Desktop.
RxJS Dynamic Interval
This file contains hidden or 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 } from 'rxjs' | |
interface TimeFn { | |
(): number | |
} | |
export function dynamicInterval(timeFn: () => number)) { | |
return new Observable(function subscribe(subscriber) { | |
let count = 0 | |
let id = setTimeout(handleTimeout, timeFn()) | |
// Probably not needed | |
let go = true | |
// How to do teardown logic? | |
return function unsubscribe() { | |
go = false | |
clearTimeout(id) | |
} | |
function handleTimeout() { | |
subscriber.next(count) | |
count++ | |
if (go) { | |
id = setTimeout(handleTimeout, timeFn()) | |
} | |
} | |
}) | |
} | |
dynamicInterval(() => Math.random() * 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use async scheduler instead of setTimeout.