The task is to implement interval which emits sequential numbers every specified period of time.
The boilerplate code:
function interval(period) {
// your code here
}
The function takes one argument - period, which is the time interval between emissions. The function returns a new Observable. When the Observable is subscribed to, an observer object that defines what to do when a new value is emitted is returned
let count = 0;
const id = setInterval(() => observer(count++), period)
The count starts at 0. At every period, setInterval runs observer(count++), and the subscriber receives a new value.
When the subscription to the Observable ends, the timer is stopped
return {
unsubcribe() {
clearInterval(id)
}
}
The final code
function interval(period) {
// your code here
return new Observable(observer => {
let count = 0;
const id = setInterval(() => observer(count++), period)
return{
unsubscribe() {
clearInterval(id)
}
}
})
}
That's all folks!
Top comments (0)