Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 setinterval() keep running on other component

Tags:

angular

People also ask

How do I repeat setInterval?

You will notice a simple trick: repeat = repeat || setInterval(reduce, 1000); This will ensure multiple intervals are not registered.

How would you stop a setInterval () once it has been set?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

How does the setInterval () function work in?

setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .

Can I use setInterval in angular?

You can use this example with angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 version. Here, i will give you very simple example of how to use setinterval and clearinterval in angular application. i will create one callMethod() and call it on every 5 seconds with console log message.


You need to use clearInterval method for this within the ngOnDestroy hook method of your component. For this you need to save the returned value by the setInterval method.

Here is a sample:

ngOnInit() {
  this.battleInit();
  this.id = setInterval(() => {
    this.battleInit(); 
  }, 5000);
}

ngOnDestroy() {
  if (this.id) {
    clearInterval(this.id);
  }
}

every 40 seconds

 polling: any;

  ngOnInit() {

    this.consulta();
    this.pollData();
  }

 pollData () {
    this.polling = setInterval(() => {
    this.consulta();

  },40*1000)

 ngOnDestroy() {
    clearInterval(this.polling);
  }