如何将Observable.timer替换为setInterval?求最优实现方案
Replacing
Observable.timer with setInterval Correctly Let me walk you through the right way to do this, since your current approach has a couple of key issues.
First, understand what the original RxJS code does
The line this._timer = Observable.timer(0, 1000).subscribe(() => { this._timerAction() }); has two critical behaviors:
- Runs
this._timerAction()immediately (the0parameter is the initial delay) - Repeats
this._timerAction()every 1000ms afterward
Your attempt's problem
Your code this._timer.subscribe(() => { setInterval(() => { this._timerAction() }, 1000); }); is mixing RxJS and vanilla JS incorrectly:
- In the original code,
this._timeris a subscription object, not an Observable—so calling.subscribe()on it will throw an error. - Even if it were an Observable, nesting
setIntervalinside a subscription would create a new interval every time the subscription emits, leading to overlapping, unmanageable intervals.
The optimal vanilla JS implementation
To replicate the exact behavior of the original RxJS code with setInterval, do this:
// Execute the action immediately (matches the 0 delay in timer) this._timerAction(); // Set up the interval to repeat every 1000ms this._timer = setInterval(() => { this._timerAction(); }, 1000);
Don't forget cleanup!
Just like you would unsubscribe from the RxJS subscription to stop the timer, you need to clear the interval when you're done (e.g., in a component's destroy lifecycle hook):
// Stop the interval and clean up the reference if (this._timer) { clearInterval(this._timer); this._timer = null; }
内容的提问来源于stack exchange,提问作者David J.
相关产品推荐
相关产品推荐

