我正在尝试创建一个p,然后有一个延迟,然后创建另一个p,我的战斗功能可以正常工作,直到我尝试添加setTimeout。我尝试过在几乎所有地方使用 setTimeout 但没有效果。有时它会创建无限循环,并且在某些地方它可能会在同时创建每个 p 之前进行延迟。
效果应该和这个类似Click Attack Button
我尝试使用与此 codepen 的创建者相同的方法,但我不明白他的代码是如何工作的。
function timeout() {
setTimeout(function() {
}, 500);
}
var battle = function() {
while (monsterHP > 0) {
var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2));
var newP = $('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (monsterHP - playerDam) + "HP left</p>");
monsterHP -= playerDam;
timeout();
if (monsterHP <= 0) {
$('#battle').append("<p>You have defeated the monster</p>");
}
}
}
$('#battleButton').click(function() {
battle();
});
最佳答案
我尝试在评论中解释,但它不合适,因为这里发生了一些事情。修复它并讨论新代码会更容易:
var battle = function() {
var i=0;
while (monsterHP > 0) {
(function(hp){
var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2));
monsterHP-= playerDam;
hp= monsterHP; // this might or might not be needed.
setTimeout(function(){
var newP = $('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (hp - playerDam) + "HP left</p>");
if (hp<= 0)$('#battle').append("<p>You have defeated the monster</p>");
}, i++ * 500);
}(monsterHP));
}
}
这里我将计算移至循环顶部,然后将计算的可见操作推迟到 setTimeout 后面 1/2 秒。
您需要由循环更改的变量的私有(private)副本,并且您需要一个可以使用这些值的超时。
关于javascript - 使用 setTimeout 强制创建新元素之间的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36342358/