所以我试图写一些javascript来倒计时,然后在倒计时结束时提交表格。这是我在网上找到的JS,并试图实现:
var seconds = 300;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.qForm.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
这里实施: https://jsfiddle.net/spadez/9p9o4k6s/1/
错误说: secondPassed未定义,但我不确定为什么会这样。有谁能解释我哪里出错了?
答案 0 :(得分:1)
代码的最后一行出错。将该行更改为此&#39;
while game.is_active:
client1 => AppEngine => OneSignal => client2
client2 => AppEngine => OneSignal => client1
这是更新的小提琴。 https://jsfiddle.net/9p9o4k6s/3/
答案 1 :(得分:1)
当您将函数调用作为字符串传递给setInterval
时,您调用的函数必须位于全局范围内。您的函数secondPassed
由jsFiddle onload包装器包装,因此它不在全局范围内。
为了证明这一点,如果您window.secondPassed = secondPassed;
将其置于全局范围内,那么您的现有代码将起作用。
正确的解决方案是将函数对象作为参数而不是字符串传递:
var countdownTimer = setInterval(secondPassed, 1000);
注意以这种方式使用时没有括号()
。
答案 2 :(得分:1)
对我而言,使用SO片段调用setInterval
的两种方式都很有效。我认为bug可以是特定于jsfiddle的,因为它似乎只接受setInterval
的第一种形式,它接受函数和间隔,而不是代码字符串来执行和延迟(https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval)。如果你想继续使用小提琴,你必须将最后一行更改为:
var countdownTimer = setInterval(secondPassed, 1000);
var seconds = 300;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.qForm.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
&#13;
body {
background-color: #eee;
}
canvas {}
time {color: red; float: right;}
.active {color: green; font-size: 12px; font-weight: bold;}
&#13;
<h3>Question 1 of 20<time id="countdown">5:00</time></h3>
<form name="qForm">
<input type="radio"> 219
<input type="submit" value="Submit">
</form>
&#13;