Angular 6 run a function in every X seconds

后端 未结 5 1404
我寻月下人不归
我寻月下人不归 2021-01-03 21:53

I have a function called

opensnack(text) { ... };

which is opening an angular material snackbar with the given text input.

What I

5条回答
  •  臣服心动
    2021-01-03 22:45

    Use interval from rxjs

    Here's how:

    import { interval, Subscription } from 'rxjs';
    
    subscription: Subscription;
    
    ...
    
    //emit value in sequence every 10 second
    const source = interval(10000);
    const text = 'Your Text Here';
    this.subscription = source.subscribe(val => this.opensnack(text));
    
    ...
    
    ngOnDestroy() {
      this.subscription.unsubscribe();
    }
    

    Alternatively, you can use setInterval which is available as method on the Window Object. So you don't need to import anything to use it.

    intervalId = setInterval(this.opensnack(text), 10000);
    
    ...
    
    ngOnDestroy() {
      clearInterval(this.intervalId);
    }
    

    Here's a SAMPLE STACKBLITZ for your ref.

提交回复
热议问题