我正在为一个类构建cli节点应用程序。当我运行它时,我陷入了一个导致堆栈溢出的无限循环。我确定这是因为提示不会等到用户在迭代之前输入输入,那么处理这个问题的最佳方法是什么?CLI节点应用程序堆栈溢出
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);
}
while循环运行速度非常快,并且在第一秒钟完成之前会创建数百个超时。 –