admin管理员组文章数量:1405301
I want to stop interval after it reaches 0, but it goes on and on...
here is my code
function timer() {
var health = 100;
var counter = 0;
if (health > 0) {
counter = setInterval(function () {
reduce = Math.floor(Math.random() * 15);
health = health - reduce;
console.log(health);
}, 1000);
} else {
clearInterval(counter);
}
}
I want to stop interval after it reaches 0, but it goes on and on...
here is my code
function timer() {
var health = 100;
var counter = 0;
if (health > 0) {
counter = setInterval(function () {
reduce = Math.floor(Math.random() * 15);
health = health - reduce;
console.log(health);
}, 1000);
} else {
clearInterval(counter);
}
}
Share
edited Jun 27, 2020 at 19:15
VLAZ
29.2k9 gold badges63 silver badges84 bronze badges
asked Jun 27, 2020 at 19:13
user11092493user11092493
1
- Is because when you enter the Interval, you cannot exit, so the scipt will never return at the else – Matteo Possamai Commented Jun 27, 2020 at 19:28
1 Answer
Reset to default 9Do the check and conditional clearInterval
inside the scheduled function:
function timer() {
var health = 100;
var counter = setInterval(function () {
var reduce = Math.floor(Math.random() * 15);
health = health - reduce;
console.log(health);
if (health < 0) {
clearInterval(counter);
}
}, 1000);
}
本文标签: javascriptSet and clear interval conditionallyStack Overflow
版权声明:本文标题:javascript - Set and clear interval conditionally - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744909144a2631807.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论