javascript - How to increment the number by setinterval in typescript - Stack Overflow

Tried to increment the number upto 10 after reached 10 again will start same like this : I tried by t

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 ++; 

}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745178464a4615307.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信