Home > Enterprise >  How to use setInterval() method to stop after executing function after "n" times
How to use setInterval() method to stop after executing function after "n" times

Time:11-11

How can use the setInterval() to call the function at the given time interval and to stop the execution of the program when the counter hits 40.

I implemented the below logic the counter gets incremented to 2 and goes to infinite loop

export class AppComponent implements OnInit  {
  name = 'Angular '   VERSION.major;
  intervalcounter :any;
  intervalsDef :any;

  ngOnInit(){
    this.intervalcounter = 1;
    this.function_with_interval();
  }


  function_with_interval(){

    this.intervalsDef =setInterval(()=> {
      console.log(this.intervalcounter);
      this.getData(); },10);

    if(this.intervalcounter == 40){
      console.log(this.intervalcounter);
      clearInterval(this.intervalsDef);
    }
    else{
      this.intervalcounter  ;
      console.log(this.intervalcounter);
    }


     
    }

    getData(){
      console.log("hello")
    }
  }

stackblitz edit link : application edit link

CodePudding user response:

Just use this and it should work. Use IF ELSE inside the interval.

function_with_interval(){

    this.intervalsDef =setInterval(()=> {
      if(this.intervalcounter == 40){
        console.log(this.intervalcounter);
        clearInterval(this.intervalsDef);
      }
      else{
        this.intervalcounter  ;
        console.log(this.intervalcounter);
      }
      console.log(this.intervalcounter);
      this.getData(); },10);

   


     
    }

Here is the link: https://stackblitz.com/edit/angular-ivy-plkhwq?file=src/app/app.component.ts

CodePudding user response:

You are checking for the function call count outside the function scheduled with setInterval. Inside the context of that function, it doesn't know that it should stop executing, while the if...else part which checks for the call count is executed only once.

Try this:

import { Component, VERSION, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular '   VERSION.major;
  intervalCounter: number;
  intervalID: number;

  ngOnInit() {
    this.intervalCounter = 1;
    this.function_with_interval();
  }

  incrementCounter(step = 1) {
    this.intervalCounter  = step;
  }

  function_with_interval() {
    this.intervalID = setInterval(() => {
      console.log(  this.intervalCounter);
      this.getData();

      if (this.intervalCounter >= 4) {
        clearInterval(this.intervalID);
      }
    }, 1000);
  }

  getData() {
    console.log('hello');
  }
}

Check out the working example here.

PS. never use any type. You are bypassing all the benefits of typescript when you do that.

  • Related