DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 46

The task is to implement interval which emits sequential numbers every specified period of time.

The boilerplate code:

function interval(period) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
}
}
Enter fullscreen mode Exit fullscreen mode

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)
        }
      }
    })
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)