Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop interval in angular?

Tags:

angular

I am using rxjs6 interval in my angular6 application.Following is my code to implement interval in angular6 app.

app.component.ts

import { interval } from 'rxjs/observable/interval';
const source = interval(1000);
const subscribe = source.subscribe(val => console.log(val));

everything works fine, but how can I stop this interval ?.When I tried with unsubscribe angular says that source.unsubscribe is not a function

like image 887
Pranab V V Avatar asked Aug 12 '18 05:08

Pranab V V


1 Answers

You need to call unsubscribe() on the subscribe variable.

//emit value in sequence every 1 second
const source = Rx.Observable.interval(1000);
//output: 0,1,2,3,4,5....
const subscribe = source.subscribe(val => console.log(val));
setTimeout(()=> subscribe.unsubscribe(), 2000);

see here: http://jsbin.com/kajenif/1/edit?js,console,output

here's a good tip from rxjs lead: https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87

like image 192
Nitsan Baleli Avatar answered Sep 17 '22 19:09

Nitsan Baleli