我正在爲一個類構建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循環運行速度非常快,並且在第一秒鐘完成之前會創建數百個超時。 –