我正在制作番茄钟定时器以帮助您更好地使用Javascript。到目前为止,我已经设法将用户的输入转换为分钟,但我似乎无法使用console.log创建倒数计时器。
警告:它似乎打破了浏览器。
这是我的小提琴:http://jsfiddle.net/tmyie/YcBh9/
使用Javascript:
var doc = document,
timer = doc.getElementsByClassName('timer')[0],
button = doc.getElementsByTagName('button')[0];
button.onclick = function () {
var input = doc.getElementById('input').value;
var speed = (input * 1000) * 60;
for (i = speed; speed > 1; i - 1000) {
console.log(i);
}
}
HTML:
<div class="timer"></div>I am going to spend
<input id="input"></input>minutes working
<button>Go!</button>
答案 0 :(得分:1)
你的for循环没有正确递增,导致无限循环。
您需要-=
而不仅仅是-
,并且当您要查看speed
时,您正在检查i
,
for (i = speed; i > 1; i -= 1000) {
答案 1 :(得分:1)
首先,你的循环不正确。停止条件为speed > 1
,但您永远不会修改speed
。此外,speed - 1000
不会做任何事情。您需要speed = speed - 1000
或speed -= 1000
来修改speed
。我想你真正想要的是:
for(i = speed; i > 1; i -= 1000) {
...
}
但是,在这种情况下最好使用setInterval
。您不想使用循环,因为JavaScript是单线程的,并且循环将锁定UI(如您所发现的)。所以你可以这样做:
button.onclick = function () {
var input = parseInt(doc.getElementById('input').value, 10);
var speed = (input * 1000) * 60;
var interval = setInterval(function() {
speed -= 1000;
console.log(speed);
if(speed <= 1) {
clearInterval(interval);
console.log("All done!");
}
}, 1000); //poll every second.
};
答案 2 :(得分:1)
请勿使用for
循环,而是使用setTimeout
。否则,循环将阻止任何进一步的代码和用户交互,包括任何更新UI以显示计时器进度的尝试。试试这个:
button.onclick = function () {
var input = doc.getElementById('input').value;
var remaining = (input * 1000) * 60;
function updateTimer() {
console.log((remaining/1000) + " seconds remaining");
remaining -= 1000;
if(remaining > 0) setTimeout(updateTimer, 1000);
}
updateTimer();
}