[英]Onclick reset setInterval
<!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秒開始增益。如何執行此操作。
setTimeout
的返回值保留在可以再次獲取的位置(當前您將其存儲在局部變量中,因此在函數結束時它會消失) clearTimeout(timer);
setTimeout
。 正如昆汀已經提到的那樣,使用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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.