gpt4 book ai didi

javascript - 如何无限重复javascript setInterval计时器两次

转载 作者:行者123 更新时间:2023-11-28 15:16:41 26 4
gpt4 key购买 nike

我正在开发一个计时器,该计时器运行设定的分钟数,然后重新开始一个休息期,倒计时,然后返回到原来的分钟数。我在逻辑上挣扎。到目前为止,我让它按照原始时间运行,然后按照中断计时器运行,但我需要帮助使其返回到原始时间并无限循环(或直到按下停止按钮)。这是我所拥有的:

    function timer(minutes, breakLength) {

--minutes;

timerId = setInterval(function() {

if (minutes >= 0) {

if (seconds > 0) {
--seconds;
}

if (seconds == 0 && minutes == 0) {
playSound();
isBreak = true;
minutes = breakLength;
$('.type').html('Break');
$('.timer').html(minutes + ':00');

};

if (seconds === 0) {
seconds = 59;
--minutes;
}

if (seconds < 10) {
seconds = '0' + seconds;
}

$('.timer').html(minutes + ':' + seconds);
}
}, 1000);

}

我怎样才能让这个重复发生?

最佳答案

在计时器函数作用域中定义一个新变量作为超时 ID 持有者(我们称之为 resetTimeout):

var resetTimeout = null;

将此附加代码添加到主函数

var runFor = 60000; // 60000ms or 1 minute

在主区间添加逻辑(第一行):

if(runFor <= 0) {
if(!resetTimeout) {
// Create a reset timeout
resetTimeout = setTimeout(function(){ runFor = 60000; resetTimeout = null; }, breakLength);
}
return;
}
else {
runFor -= 1000; // Deduct time of this interval
}

此逻辑从 runFor 中扣除 1000 毫秒或 1 秒,直到完全消耗。然后创建一个 timeOut 函数,将其重置回原始值并返回当前函数,直到 runFor 被更新。我使用 60000 毫秒作为示例,您可以在下面的完整代码中看到正确的版本。为什么我们将超时分配给变量?很简单,我们不想创建多个超时。我们将超时设置为空,以允许在下一个时间间隔重新进行游戏。

请注意,有更好的方法可以做到这一点,但我决定对代码进行尽可能少的修改。

这是工作代码:

function timer(minutes, breakLength) {
var seconds = 0;
var originalMinutes = minutes;
var resetTimeout = null;
var totalRunFor = minutes * 60 * 1000; // Since minutes are independent
var runFor = totalRunFor;

timerId = setInterval(function() {
if(runFor <= 0) {
if(!resetTimeout) {

// Create a reset timeout
resetTimeout = setTimeout(function(){ runFor = totalRunFor; resetTimeout = null; }, breakLength);
}
return;
}
else {
runFor -= 1000; // Deduct time of this interval
}

if (minutes >= 0) {

if (seconds > 0) {
--seconds;
}

if (seconds == 0 && minutes == 0) {
//playSound();
isBreak = true;
minutes = originalMinutes;
$('.type').html('Break');
$('.timer').html(minutes + ':00');

};

if (seconds === 0) {
seconds = 59;
--minutes;
}

$('.timer').html(minutes + ':' + ((seconds < 10)?'0':'') + seconds);
}
}, 1000);

}
timer(1, 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run for a minute and stop for 10 seconds indefinitely.
<div class='type'></div>
<div class='timer'></div>

关于javascript - 如何无限重复javascript setInterval计时器两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33590061/

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