gpt4 book ai didi

javascript - 在javascript中从倒计时中添加/减去时间

转载 作者:行者123 更新时间:2023-11-28 05:44:21 25 4
gpt4 key购买 nike

我正在尝试弄清楚 javascript ...目前,我正在使用倒计时器。我想在按下左键或右键时加/减 1 分钟。

我尝试了以下方法:

  $(document).keydown(function(e) {
switch(e.which) {
case 37: // left
current = parseInt($('#time2').textContent);
newtime = current + 60;
countdown_start(newtime)
break;

case 39: // right
alert('right');
break;

default: return;
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});

但它有一些非常奇怪的 react ...并开始倒计时两次...其中一个带有 NaNaNaNa...

如有任何帮助,我们将不胜感激。谢谢!

.background-countdown
#start-game
= submit_tag 'Play', id: "start"
#time2
60:00
.test
asd
-##start-time
-# =text_field_tag 'start-time-input', "60:00", id: "start-time-input"

#hint-text.white-text

:javascript

function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var countdown = 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) {
$('#start').show()
$('#start-time').show()
clearInterval(countdown)
}
}, 1000);
}
function countdown_start(sixtyMinutes = 3600) {
$(document).ready(function () {
display = document.querySelector('#time2');
startTimer(sixtyMinutes, display);
});
}

$('#start').click(function() {
countdown_start()
$('#start').hide()
event.preventDefault();
});

function get_text(){
var feedback = $.ajax({
type: "POST",
url: "/jquery/update_text",
async: false
}).complete(function(){
setTimeout(function(){get_text();}, 1000);
}).responseText;
}

$(function(){
get_text();
});

最佳答案

这里的问题可能是,您正确使用了clearInterval,但没有正确保存setIntervall方法返回的ID值。

请查看 w3schools.com 页面: http://www.w3schools.com/jsref/met_win_clearinterval.asp

他们在定义下写了注释:

Note: To be able to use the clearInterval() method, you must use a global variable when creating the interval method

您在本地保存了您的 ID,因此也许您不应该这样做。相反,使用全局变量,这仅意味着您在函数部分之外声明它并一遍又一遍地使用该引用,但您还想更改的是您的顺序。首先,您设置一个间隔,然后在 startMethod 函数中清除相同的间隔。我认为如果你改变顺序并使变量成为全局变量,它应该可以工作。

关于javascript - 在javascript中从倒计时中添加/减去时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38669034/

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