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
2 Answers
Reset to default 1You 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
版权声明:本文标题:javascript - How to increment the number by setinterval in typescript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745178464a2646354.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论