javascript - 有条件地设置和清除间隔
问题描述
我想在它达到0后停止间隔,但它会一直持续......
这是我的代码
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);
}
}
解决方案
clearInterval
在预定函数中执行检查和条件:
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);
}
推荐阅读
- jquery - 当我尝试在 WordPress 中使用 AJAX 加载帖子时,为什么会收到 400 错误?
- couchdb - 即使手动指定芒果索引“不包含此查询的有效索引”
- kubernetes - Superset Helm Chart 在哪里?
- java - Docker 问题:仅在 Docker 中将 HTML 转换为 Java 中的图像时,UTF-8 字符无法正确显示
- python - file.read() 输出字符串位置?
- c# - 在 Azure Function 中为 Azure 服务总线输出绑定创建自定义转换器
- react-native - 如何使用 ValidationComponent 在 React Native 中添加自定义验证规则和自定义错误消息?
- c - 比较两个具有不同 int 值的 bool
- windows - 应用程序定义的消息 ID 是否应该是唯一的?
- webpack - webpack 5 display-modules 选项停止工作