您没有描述实际问题,所以我不太确定该如何回应,但这里有一些可能有用的注释。
timedCount 函数是准定时递归的。如果你喜欢的话这很酷连续传球风格,但没有必要,可能比 JavaScript 需要的更令人困惑,并且在没有尾递归堆栈清理的语言中会浪费一些资源(堆栈帧)(不知道 JS 是否有这样的功能或不是)。
由于这是一个重复的函数执行,您可以使用setInterval代替setTimeout
,并有一个重复的函数调用来检查它是否应该增加并重新显示计数...如下所示:
var c=0;
var timer_is_on=false;
function displayCount() {
document.getElementById('txt').value=c;
}
function count() {
if(timer_is_on) {
c=c+1;
displayCount();
}
}
var interval = setInterval(count,1000);
现在,解决问题的单按钮部分。假设有一个按钮:
<input type="button" value="Start count!" onclick="toggle" />
当我们点击它时,我们希望“值”属性发生变化,并且我们希望它翻转timer_is_on
多变的。让我们创建一个执行所有这些操作的函数:
function toggle() {
if(timer_is_on) {
timer_is_on = false;
this.value = "Start count!"; // `toggle` is invoked by the button's event handler, so `this` is the button
} else {
timer_is_on = true;
this.value = "Stop count!";
}
}
所以... count总是每1000ms执行一次,但它只在timer_is_on时执行任何操作,并且timer_is_on是否为true或false由toggle
,它附加到我们的按钮上。我想稍微简单一点。
UPDATE
如果我们想要怎么办not有功能count
总是在后台运行?正如 Tom Tu 指出的,这可能代表 CPU 开销。我不确定它是一个可测量的(或者它代表超出浏览器可能运行的用于执行其自己的 UI 更新的计时器的任何开销),但它在某些平台上可能很重要,因此可能值得解决。
当我们正在完善时,我不太喜欢自己通过标签属性附加事件处理程序,或者如果可以避免的话,将变量放入全局/窗口范围中,所以我可能会将所有相关的计数器设置/处理 JavaScript 包装在里面一大setupCounter
功能,并附加toggle
函数到onclick
使用 DOM 选择和 JavaScript 的输入按钮事件。我可能会尝试只运行document.getElementById
也每个查找一次。
所以,假设按钮输入有 idstartstop
但否则假设类似的标记。我可能会做这样的事情:
function setupCounter() {
var c=0,
interval,
counter_display = document.getElementById('txt'),
button = document.getElementById('startstop');
function display_count() {
counter_display.value = c;
}
function count() {
c=c+1;
display_count();
}
function toggle() {
if(!interval)
interval = setInterval(count,1000);
button.value = "Stop count!";
else {
clearInterval(interval);
interval = false;
button.value = "Start count!";
}
}
button.onclick = toggle;
}
然后你会打电话setupCounter
在声明 counter_display 和 startstop 元素之后的某个时间,或者将其分配给window.onload
事件或将其传递给类似 jQuery 的东西$(document).ready()
.