【发布时间】:2020-12-01 00:30:15
【问题描述】:
我想知道如果正在执行的功能正在运行,我如何能够停止单击按钮。这是我的 JS 代码:
let money = 0;
let running = false;
function start(time, val) {
if (running == false) {
running = true;
console.log(running)
let bar = document.getElementById('progressBar1');
bar.value = time;
time++;
let sim = setTimeout("start(" + time + ")", 30);
if (time == 100) {
bar.value = 0;
let id = val;
money++;
document.getElementById("moneyValue").innerHTML = money;
clearTimeout(sim);
running = false;
}
} else if (running == true) {
console.log("Already Growing!");
};
}
<progress id="progressBar1" value="0" max="100" style="width:150px;"></progress>
<button id="restart-button" class="plantBtn" onclick="start(0, this.id)">Plant Seed</button>
它的作用是启动一个进度条(progress div)。我希望该按钮提醒一条消息,说已经开始或类似的东西。
我遇到的问题是它正在跳转到 else if 语句,并且没有运行任何东西。奇怪的是,如果我将 console.log 添加到 if 语句的中间,它会起作用。
我认为这是因为该条需要时间来填充,如果用户单击它,它永远不会满,因为它会跳转到 else if 语句并取消 if 函数。 (只有在 bar 达到 100% 后才会再次变为 false)
有人可以帮忙吗?我对 JS 或 Jquery 持开放态度(对此有点生疏)。
谢谢
【问题讨论】:
-
你多了一个花括号;而不是
} else if (running == true) {你只需要else if (running == true) { -
不,那个大括号链接到另一个 if 语句(在第一个内部)
-
为什么要调用同一个函数?超时后的代码应该和超时一起调用,而不是调用启动它的逻辑
-
什么?每次单击按钮时。所以该按钮将被多次点击,但我不希望它在前一个完成之前执行该操作
-
@epascarello 你能演示一下吗?
标签: javascript html button boolean progress-bar