我想知道如何在继续计算我所拥有的“糖果”数量之前,每秒循环暂停一次。
编辑:我想暂停,以便每秒钟我的糖果量增加1.目前显示器开始显示1到10.我试图复制这里完成的效果(我很新JavaScript):http://candies.aniwey.net/
//booleans
var count = new Boolean;
count = true;
//integers
var candy = 0;
//strings
var txt = "You have ";
var txt1 = " candies.";
var br = "<br>";
//loops
while (candy <= 10) {
if (candy == 0) {
document.write(txt + candy + txt1);
document.write(br);
candy++;
} else if (candy == 1) {
document.write(txt + candy + " candy.");
document.write(br);
candy++;
} else {
document.write(txt + candy + txt1);
document.write(br);
candy++;
}
}
答案 0 :(得分:1)
var candy = 0;
window.setInterval(function() {
document.write("You have " + ++candy + " candy.<br/>");
}, 1000);
答案 1 :(得分:0)
使用setTimeout
来调用函数(jsfiddle)
var candy = 0;
function moreCandy() {
document.getElementById('textHere').innerHTML += 'You have ' + candy +
(candy == 1 ? ' candy' : ' candies') + '<br />';
candy++;
if (candy <= 10) {
setTimeout(moreCandy, 1000);
}
}
moreCandy();
for (var i = 0; i <= 10; i++) {
setTimeout(getCandy(i), i * 1000);
}
function getCandy(amount) {
return function () {
document.getElementById('textHere').innerHTML +=
'You have ' + amount +
(amount == 1 ? ' candy' : ' candies') + '<br />';
};
}
答案 2 :(得分:-1)
无法暂停执行JavaScript。您需要重构此代码以改为基于计时器调用函数。
顺便说一句 - 永远不要永远不要使用document.write。使用DOM方法,如.innerHTML。