我正在为一个班级构建一个cli Node应用程序。当我运行它时,我陷入无限循环,导致堆栈溢出。我确定这是因为提示不会等到用户在迭代之前输入输入,那么处理这个问题的最佳方法是什么?
var prompt = require('prompt');
prompt.start();
// initialize fields
var user = {
health: 100,
damage: Math.floor(Math.random() * (5 - 2 + 1)) + 2
},
zombie = {
health: 20,
damage: Math.floor(Math.random() * (5 - 2 + 1)) + 2
};
while (user.health > 0 || zombie.health > 0) {
setTimeout(function() {
console.log('User:\t' + user.health + '\nZombie:\t' + zombie.health);
var randNum = Math.random * 10;
prompt.get(['guess'], function(err, result) {
if (result.guess === randNum) {
zombie.health -= user.damage;
console.log('You strike the Zombie!\nZombie takes ' + user.damage + ' points of damage.\nZombie has ' + zombie.health + 'health left.\n');
}
else {
user.health -= zombie.damage;
console.log('Zombie slashes at you!\nYou take ' + zombie.damage + ' points of damage.\nYou have ' + user.health + ' health left.\n');
}
console.log('Tomorrow is another day...\n');
});
}, 1000);
}
答案 0 :(得分:1)
收到提示后,让函数自行调用。例如:
$rootScope.test
答案 1 :(得分:0)
while循环非常快。在第一秒完成第一个之前,它将创建数百个setTimouts。