gpt4 book ai didi

Javascript 倒计时与暂停和恢复

转载 作者:行者123 更新时间:2023-12-02 14:22:33 30 4
gpt4 key购买 nike

我有 JavaScript 倒计时

var timersCount = 0;
var timerCounter = setInterval(countTimers, 30000);
countTimers();

function countTimers()
{
timersCount++;

var count = 26;
var counter = setInterval(timer, 1000);
function timer()
{

count = count-1;
if(count < 0) {
clearInterval(counter);
return;
}

document.getElementById("timer").innerHTML=count;
}

document.getElementById("countTimers").innerHTML=timersCount;
}

HTML

<button id="pause">Pause</button>
<button id="resue">Resume</button>

该功能运行正常。但现在我想添加暂停和恢复倒计时。是否可以将其设置为我的功能。请帮忙。

最佳答案

给你。首先,您只需要一个间隔,其次您应该有一些标志告诉您计时器何时暂停。那么它只是简单的逻辑和 2 个监听器。

var timersCount = 0;
var pause = false; //is timer paused

countTimers();

function countTimers() {
timersCount++;

var count = 26;
var counter = setInterval(timer, 1000);

function timer() {
if (!pause) { //do something if not paused
count = count - 1;
if (count < 0) {
clearInterval(counter);
setTimeout(countTimers, 5000); //start count from 26 again
return;
}

document.getElementById("timer").innerHTML = count;
}
}

document.getElementById("countTimers").innerHTML = timersCount;
}

document.getElementById('pause').addEventListener('click', function () {
pause = true;
});

document.getElementById('resume').addEventListener('click', function () {
pause = false;
});
<span id="timer"></span>
<span id="countTimers"></span>
<button id="pause">Pause</button>
<button id="resume">Resume</button>

关于Javascript 倒计时与暂停和恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38539000/

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