我的代码遇到了一些麻烦。我似乎无法获得倒数秒的秒循环。你需要在一个数字的末尾有多少个零来获得1秒?
var Time = Math.floor((Math.random() * 1500000) + 500000); // trying to make this use seconds not whatever it uses /\
console.log(Time / 100000);
//defining a random variable
while (Time >= 0) {
if (Time == 0) {
document.write("done");
}
Time--;
}
答案 0 :(得分:1)
在循环中使用cpu
循环逻辑以定义倒计时的秒数并不是一个好主意。
您可以使用setInterval
功能,如下所示:
var seconds = 10;
var timer = setInterval(function() {
seconds--;
if(seconds == 0) {
document.write("done");
clearInterval(timer);
} else {
document.write(seconds + " seconds left");
}
}, 1000);
答案 1 :(得分:0)
这是我的实施
//param 10 is the amount of seconds you want to count down from
countdown(10);
function countdown(x) {
if(x) {
console.log(x+ " seconds left...");
// will call itself until x=0
setTimeout(countdown, 1000, --x);
} else {
// no timer needed to be cleaned up
console.log("Done...");
}
}