Skip to content

Instantly share code, notes, and snippets.

@jacksteamdev
Last active June 4, 2020 19:18
Show Gist options
  • Save jacksteamdev/49bdac75eccd1d9de5f230986a70a233 to your computer and use it in GitHub Desktop.
Save jacksteamdev/49bdac75eccd1d9de5f230986a70a233 to your computer and use it in GitHub Desktop.
RxJS Dynamic Interval
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)
@jacksteamdev
Copy link
Author

Use async scheduler instead of setTimeout.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment