重置 JavaScript 函数

Reset javascript function

本文关键字:函数 JavaScript 重置      更新时间:2023-09-26

我在 onclick 事件后让 javascript 函数重置自身时遇到问题。当我单击"开始"按钮时,计数器开始计数。但是当我单击"重置"按钮时,没有任何反应。我需要计时器重置为"0:00"并等待我再次单击"开始"。这是我的代码:

<script type="text/javascript">
var seconds = 0;
var minutes = 0;
function zeroPad(time) {
    var numZeropad = time + '';
    while(numZeropad.length < 2) {
        numZeropad = "0" + numZeropad;
    }
    return numZeropad;
}
function countSecs() {
    seconds++;
    if (seconds > 59) {
         minutes++;
         seconds = 0;
    }
    document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
 function startTimer() {
     action = window.setInterval(countSecs,1000);
 }

function resetTimer() {
    var seconds = 0;
    var minutes = 0;
 }
</script>
<body>
<button onclick = "startTimer()">Start</button>
<div id="timeBox">Time 00:00</div>
<button onclick = "resetTimer">Reset</button>
</body>

调用 clearInterval() 方法。

function resetTimer() {
   window.clearInterval(action);
 }

这是一个范围问题,在函数中使用 var 会使分钟成为该函数的本地。 删除前导变量将使您朝着正确的方向开始。

function resetTimer() {
  seconds = 0;
  minutes = 0;
}

Onclick 事件必须调用如下函数: 末尾带有括号的onclick="resetTimer();"。如果您未定义type="button",某些浏览器可能会尝试在单击按钮时提交。我不认为您希望重置计时器来停止计时器,所以我添加了一个停止按钮。

http://jsfiddle.net/iambriansreed/WRdSK/

<button type="button" onclick="startTimer();">Start</button>
<div id="timeBox">Time 00:00</div>
<button type="button" onclick="resetTimer();">Reset</button>
<button type="button" onclick="stopTimer();">Stop</button>
<script>
    window.seconds = 0;
    window.minutes = 0;
    function startTimer() {
        window.action = setInterval(countSecs,1000);
    }
    function resetTimer() {
        seconds = 0;
        minutes = 0;
    }
    function stopTimer() {
        clearInterval(action);        
        seconds = -1;
        minutes = 0;
        countSecs();
    }
    function zeroPad(time) {
        var numZeropad = time + '';
        while(numZeropad.length < 2) {
            numZeropad = "0" + numZeropad;
        }
        return numZeropad;
    }
    function countSecs() {
        seconds++;
        if (seconds > 59) {
             minutes++;
             seconds = 0;
        }
        document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
    }
</script>

代码中有两个错误:

首先,在按钮中,您错过了函数名称后的(),以便进行实际调用:

<button onclick = "resetTimer()">Reset</button>

其次,您没有使用window.clearInterval()(MDN 文档)停止间隔,因此计时器一直在继续。

// just to make it an explicit global variable. already was an implicit one.
var action;
// rest of your code
function resetTimer() {
    // clear the timer
    window.clearInterval( action );
    // reset variables
    var seconds = 0;
    var minutes = 0;
    // update output
    document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
 }

我在这里设置了一个工作小提琴。