我的脚本运行了,但是当它到达 setTimeout 部分时,它只是不喜欢它:( 浏览器崩溃了,我必须退出。是浏览器错误还是我没搞错?
var health=100;
var ehealth=100;
var atk;
var eatk;
function attack(x){
x=Math.floor(Math.random()*11);
atk=x;
ehealth=ehealth-atk
document.write('Enemy Health:' + ' ' + ehealth + ' ')
}
function eattack(x){
x=Math.floor(Math.random()*11);
eatk=x;
health=health-eatk
document.write('Health:' + ' ' + health )
}
function dead(){
if(health<=0){
document.write('You Lose');
}else{
if(ehealth<=0){
document.write('You Win');
}
}
}
function battle(){
document.write('Enemy Health:' + ' ' + ehealth + ' Health: ' + health + '<br/>\n')
while(health>=0&&ehealth>=0){
setTimeout(function(){
attack(0)
},400)
setTimeout(function(){
eattack(0)
},400)
document.write("<br/>\n");
dead();
}
}
我该怎么办:(
最佳答案
您的 while 循环不会终止。你触发了无穷无尽的 setTimeout() 回调,但由于 JS 仅在一个线程中执行,因此这些回调都不会被执行。
让我们更详细地看看会发生什么:
在事件循环(要执行的JS代码的队列)中,首先只有你的战斗函数。
在 while 循环第一次迭代之后,事件循环仍然如下所示:
battle | attack | eattack
使用 setTimeout()
的函数在 battle()
函数后面排队。下一次迭代后,它看起来像这样
battle | attack | eattack | attack | eattack
但仍然没有执行 (e)attack()
函数,因此 health
和 ehealth
变量保持不变。这种情况会一直持续下去,直到您的浏览器耗尽所有内存并崩溃。
作为解决方案,我建议引入这样的内容:
function battleRound() {
attack(0);
eattack(0);
dead();
if( health>=0&&ehealth>=0 ) {
// still a round to go
setTimeout( battleRound, 400 );
}
}
不用排队多个函数,只需将一轮又一轮的战斗加入队列,直到战斗结束。
关于javascript - 我的脚本使浏览器崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19517134/