Onclick重置setInterval

时间:2013-08-16 06:27:19

标签: javascript jquery

<!DOCTYPE html>
<html>
<head>
<script>

function timer(x) {
    if (x == 1) {
        //reset timer 
        }
    var i = 0;
    var timer = setInterval(function() {

        var x = document.getElementById("demo").innerHTML = i;
        i = i + 1;

    }, 500);
}

</script>
</head>
<body>


<p id="demo">hello</p>

<button type="button" onclick="timer(0)">change</button>

<button type="button" onclick="timer(1)">reset</button>

</body>
</html> 

我想重置计时器onclick。例如如果setIntervaltime设置为5秒并且经过了3秒,那么如果有一些点击重置按钮,它应该从5秒开始增益。如何做到这一点。

2 个答案:

答案 0 :(得分:6)

  1. setTimeout的返回值保留在可以再次获取的位置(目前您将其存储在局部变量中,因此当函数结束时它会消失)
  2. 致电clearTimeout(timer);
  3. 再次使用您想要的任何参数调用setTimeout

答案 1 :(得分:1)

正如Quentin所提到的,使用clearInterval来解决您的问题。

将其包含在if.else..语句中,如

if(x == 1) {
   clearTimeout(timeout);
}
else {
    timeout = setInterval.....  // otherwise even after resetting
                                // it will continue to increment the value
}

完整代码:

var timeout;  // has to be a global variable
function timer(x) {
    var i = 0;
    if (x == 1) {
        clearTimeout(timeout);
        document.getElementById("demo").innerHTML = i;
    } else {
        timeout = setInterval(function () {
            var x = document.getElementById("demo").innerHTML = i;
            i = i + 1;
        }, 1000);
    }
}

JSFiddle