This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
72. implement Observable interval()
Solution:
function interval(duration) {
let count = 0;
return new Observable(observer => {
const intervalId = setInterval(() => {
observer.next(count++);
}, duration);
return () => {
clearInterval(intervalId);
}
});
}
We first declare a count
variable which will keep track of the sequential numbers emitted by the Observable. Then, we return a new Observable with a function that takes an observer as an argument. We use setInterval()
to emit the sequential numbers every duration
seconds and pass them to the observer using observer.next()
. We also return a clean-up function to clear the interval using clearInterval()
when the observer unsubscribes.