gpt4 book ai didi

javascript - 单击按钮后计时器应再次启动

转载 作者:行者123 更新时间:2023-11-30 14:32:32 25 4
gpt4 key购买 nike

<script>
var minutes = 1;
var seconds = 45;


$(document).ready(function () {
setInterval(startTimer, 1000);
});

function startTimer() {


document.getElementById("timer").innerHTML = (minutes - 1) + ":" + --seconds;
if (seconds == 0) {
minutes--;
if (minutes != 0) {
seconds = 60;
} else {
seconds = 0;
}

}
if (minutes == 0 && seconds == 0) {
document.getElementById('next').click();
minutes = 1;
seconds = 45;

}


}
</script>

这是我的计时器代码,它应该在单击 ID 为 #next 的按钮后重新启动。我做了很多事情,但都行不通。请帮忙。

按钮 ID = 下一步

最佳答案

这是我对您的问题的解决方案。

I've noticed $(document).ready() so I instantly presumed you are using jQuery.

var timerInterval 是对您启动的计时器的直接引用。

要停止计时器,请使用 clearInterval(timerInterval) [同样的故事也适用于 setTimeout()]。

我已经更改了您的倒数计时器,因为我懒得去修理它。


var timerInterval;

let minutes = 2;
let seconds = 42;

let duration = (minutes * 60) + seconds;
let display = document.querySelector('#timer');

function startTimer(duration, display) {
var timer = duration, minutes, seconds;
timerInterval = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);

minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

display.textContent = minutes + ":" + seconds;

if (--timer < 0) {
timer = duration;
clearInterval(timerInterval);
}
}, 1000);
}

startTimer(duration, display);

$('button').click((e) => {
clearInterval(timerInterval);
startTimer(duration, display);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>
<br>
<button>Reset Timer</button>

关于javascript - 单击按钮后计时器应再次启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50951518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com