我的脚本使浏览器崩溃
My script crashes the browser
我的脚本运行,但是当它到达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 );
}
}
与其排队众多功能,不如排队一轮又一轮战斗,直到战斗结束。
问题是你的while循环:
while(health>=0&&ehealth>=0){
setTimeout(function(){
attack(0)
},400)
您正在设置攻击功能以执行"无限"时间。
通常,您的代码会尝试设置无限数量的超时处理程序。
setTimeout 设置一些函数将来要运行,但它立即结束运行,不会等到函数运行。因此,虽然循环无限运行,因为内部没有任何东西可以改变健康。
其他更好的解决方案是使用间隔 - 例如:
var game_interval;
function turn () {
attack(0);
eattack(0);
if (health<=0 || ehealth<=0) {
clearInterval(game_interval);
dead();
}
}
game_interval = setInterval(400,turn);
turn(); // first turn immediately
相关文章:
- location.reload(true)崩溃浏览器选项卡
- 为什么这个For循环会使浏览器实验室崩溃
- 脸书's的inApp浏览器在尝试上传表单中的照片时崩溃
- 为什么这会造成一个无休止的循环并使我的浏览器崩溃
- jQuery文件上传崩溃的浏览器
- javascript audio currentTime使一些浏览器崩溃
- 在浏览器崩溃之前检测到内存耗尽
- 浏览器11上的Javascript location.href崩溃
- Javascript游戏与循环崩溃浏览器
- 输入输入前浏览器崩溃
- 写得不好的jQuery正在崩溃浏览器
- Ajax 自动完成冻结/崩溃浏览器
- 简单Greasemonkey脚本崩溃浏览器
- 重构jQuery以淡出并阻止其崩溃浏览器
- 为什么这个崩溃浏览器选项卡
- Javascript和细分,在for循环中崩溃浏览器
- 桌面图像拖放上传崩溃浏览器
- 可处理的更新单元格崩溃浏览器
- 简单的页面崩溃浏览器
- ASP.NET 中的角崩溃浏览器