最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

}
发布评论

评论列表(0)

  1. 暂无评论