The behavior of delay, timer, interval operators seems to be the same in RxJS. Can anyone let me know what is the difference between those operators?
delay
of('e').pipe(delay(2000)).subscribe(...)
- emit e
after 2 seconds.Demo
var { of } = rxjs;
var { tap, delay } = rxjs.operators;
var displayBox = document.getElementById('display');
of('e').pipe(
tap(_ => displayBox.innerHTML = 'Source observable emitted.'),
delay(2000)
).subscribe(
_ => displayBox.innerHTML += '<br />Received emission in subscription.',
null,
() => displayBox.innerHTML += '<br />Observable complete.'
);
<script src="https://unpkg.com/[email protected]/bundles/rxjs.umd.min.js"></script>
<p id="display"></p>
interval
interval(2000).subscribe(...)
- starting after 2 seconds, emit every 2 seconds.Demo
var { interval } = rxjs;
var displayBox = document.getElementById('display');
interval(2000).subscribe( // won't complete
value => displayBox.innerHTML += '<br />Received emission in subscription: ' + value
);
<script src="https://unpkg.com/[email protected]/bundles/rxjs.umd.min.js"></script>
<p id="display"></p>
timer
timer(initialDelay)
- emit once after the delay and complete.
timer(2000).subscribe(...)
- emit after 2 seconds and complete.timer(initialDelay, period)
- starting after initial delay, emit every given time period.
timer(0, 2000).subscribe(...)
- starting immediately, emit every 2 seconds.timer(2000, 2000).subscribe(...)
- starting after 2 seconds, emit every 2 seconds (similar to interval(2000)
).Demo
var { timer } = rxjs;
var timerNoDelayBox = document.getElementById('timerNoDelay');
var timerDelayBox = document.getElementById('timerDelay');
// w/o initial delay
timer(0, 2000).subscribe( // won't complete
value => timerNoDelayBox.innerHTML += '<br />Received emission in subscription: ' + value
);
// w/ initial delay
timer(2000, 2000).subscribe( // won't complete
value => timerDelayBox.innerHTML += '<br />Received emission in subscription: ' + value
);
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
width: 50%;
}
<script src="https://unpkg.com/[email protected]/bundles/rxjs.umd.min.js"></script>
<table>
<tr>
<th>Timer w/o initial delay</th>
<th>Timer w/ initial delay</th>
</tr>
<tr>
<td>
<p id="timerNoDelay"></p>
</td>
<td>
<p id="timerDelay"></p>
</td>
</tr>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With