admin管理员组

文章数量:1414628

Tried to increment the number upto 10 after reached 10 again will start same like this : /
I tried by typescript but not working. How to do it?

count:number=0;
ngOnInit(){ 
  setInterval(this.myCount,500); 
}

myCount() {

  if (this.count > 10) {
          this.count = 0;
    }
   console.log("Count form 0 to 10"+this.count);  
    this.count ++; 

}

Demo: /app/appponent.ts

Tried to increment the number upto 10 after reached 10 again will start same like this : http://jsfiddle/dRMrL/
I tried by typescript but not working. How to do it?

count:number=0;
ngOnInit(){ 
  setInterval(this.myCount,500); 
}

myCount() {

  if (this.count > 10) {
          this.count = 0;
    }
   console.log("Count form 0 to 10"+this.count);  
    this.count ++; 

}

Demo: https://stackblitz./edit/angular-kma3tn?file=src/app/app.ponent.ts

Share Improve this question asked Feb 23, 2020 at 10:31 Kavitha KKavitha K 751 gold badge1 silver badge12 bronze badges 1
  • Just convert myCount function as Fat arrow from normal function – balmukund kumar Commented Feb 23, 2020 at 12:48
Add a ment  | 

2 Answers 2

Reset to default 1

You could take a closure over the counter and the max number.

Inside of the function increment counter, take an output and adjust counter with max value.

const count = (max, counter = 0) => () => {
        console.log(counter);
        counter = counter === max ? 0 : counter + 1;
    };

setInterval(count(10), 500);

Without a closure, but with a global variable.

var counter = 0;

setInterval(() => {
    console.log(counter);
    counter = counter === 10 ? 0 : counter + 1;
}, 500);

The this keyword in your myCount refers the the setInterval function. You can solve this by using an arrow function expression in your setInterval and call your myCount method inside the arrow function.

This way the this keyword inside myCount refers to your ponent.

ngOnInit(){ 
  setInterval(() => {
    this.myCount();
  }, 500);
}

myCount() {

  if (this.count > 10) {
        this.count = 0;
  }
  console.log("Count form 0 to 10 - " + this.count);  
  this.count ++; 

}

本文标签: javascriptHow to increment the number by setinterval in typescriptStack Overflow