Ras*_*der 4 html javascript timer minute countdown
我正在尝试构建一个打字测试,当用户按下文本区域中的按键时,该测试就开始倒计时。我认为 if-else 循环有助于在 HTML 中显示并启动 1 分钟倒计时器,但事实并非如此。
请向我解释我做错了什么以及如何纠正我的代码。
HTML:
<div id="timer"></div>
<p>Text for typing test will go here.</p>
<textarea id="textarea" rows="14" cols="150" placeholder="Start typing here...">
</textarea>`
Run Code Online (Sandbox Code Playgroud)
JS:
var seconds=1000 * 60; //1000 = 1 second in JS
var min = seconds * 60;
var textarea = document.getElementById("textarea").onkeypress = function() {
myFunction()
};
//When a key is pressed in the text area, update the timer using myFunction
function myFunction() {
document.getElementById("timer").innerHTML =
if (seconds>=0) {
seconds = seconds--;
} else {
clearInterval("timer");
alert("You type X WPM");
}
} //If seconds are equal or greater than 0, countdown until 1 minute has passed
//Else, clear the timer and alert user of how many words they type per minute
document.getElementById("timer").innerHTML="0:" + seconds;
Run Code Online (Sandbox Code Playgroud)
您的代码中有很多语法错误。您需要使用setIntervalfunction 来启动函数的连续调用。更重要的是,
var seconds = 1000 * 60; //1000 = 1 second in JS
var min = seconds * 60;
Run Code Online (Sandbox Code Playgroud)
这些计算是另一个问题。
1000 * 60意思是60 seconds,所以seconds * 60给你60 minutes。
正如其中一位评论所说,there are syntax errors all over the place.. 您需要更深入地了解使用 JavaScript 进行编码。
var seconds = 1000 * 60; //1000 = 1 second in JS
var min = seconds * 60;
Run Code Online (Sandbox Code Playgroud)
var seconds = 1000 * 60; //1000 = 1 second in JS
var textarea = document.getElementById("textarea");
var timer;
textarea.addEventListener("keypress", myFunction)
//When a key is pressed in the text area, update the timer using myFunction
function myFunction() {
textarea.removeEventListener("keypress", myFunction);
if(seconds == 60000)
timer = setInterval(myFunction, 1000)
seconds -= 1000;
document.getElementById("timer").innerHTML = '0:' + seconds/1000;
if (seconds <= 0) {
clearInterval(timer);
alert("You type X WPM");
}
} //If seconds are equal or greater than 0, countdown until 1 minute has passed
//Else, clear the timer and alert user of how many words they type per minute
document.getElementById("timer").innerHTML= "0:" + seconds/1000;Run Code Online (Sandbox Code Playgroud)
我注意到您的解决方案存在一些问题。
1)你clearInterval,但你从未setInterval
2)秒=秒--,由于JavaScript中的操作顺序,它并没有像你想象的那样做。
我修改了你的 JS,并在这个codepen中有一个可行的解决方案
JS:
var seconds=60;
var timer;
function myFunction() {
if(seconds < 60) { // I want it to say 1:00, not 60
document.getElementById("timer").innerHTML = seconds;
}
if (seconds >0 ) { // so it doesn't go to -1
seconds--;
} else {
clearInterval(timer);
alert("You type X WPM");
}
}
document.getElementById("textarea").onkeypress = function() {
if(!timer) {
timer = window.setInterval(function() {
myFunction();
}, 1000); // every second
}
}
document.getElementById("timer").innerHTML="1:00";
Run Code Online (Sandbox Code Playgroud)