问题描述
这又是我的剪刀石头布游戏。
This again is my Rock Paper Scissors game.
当前状态下,用户无法看到正在发生的事情,因为在提示输入后(岩石,剪刀或剪刀) ),他们会立即得到提示。
At present state the user can't see what's happening because after being prompted for input(Rock, Paper or Scissors) they are immediately reprompted.
问题是我如何使程序延迟,以便他们至少可以阅读正在发生的事情。
The question is how can I make the program delay such that they at least can read what's going on.
我读过JavaScript中不存在sleep()。我正在尝试使用setTimeOut,但是setTimeOut导致程序无法运行。
I've read that sleep() does not exist in JavaScript. I'm trying to use setTimeOut however, the setTimeOut is causing the program to not run.
关于如何在第一个用户输入之后如何延迟下一个用户输入的任何想法。
这是我目前的代码
function playUntil(rounds) {
var playerWins = 0;
var computerWins = 0;
setTimeout(function() {
while ((playerWins < rounds) && (computerWins < rounds)) {
var computerMove = getComputerMove();
var winner = getWinner(playerMove, computerMove);
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "Player") {
playerWins += 1;
}
else if (winner === "Computer") {
computerWins += 1;
}
if ((playerWins == rounds) || (computerWins == rounds)) {
console.log("The game is over! The " + winner + " has taken out the game!");
console.log("The final score was Player - [" + playerWins + "] to Computer - [" + computerWins + "]");
}
else {
console.log(winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
return [playerWins, computerWins]
;},5000);
}
推荐答案
这花了我很长时间找出答案,但这是解决方案。
This took me a long time to figure out but here was the solution.
创建此函数
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
将此添加到我想要延迟的代码中
Add this into my code where I wanted the delay
sleep(3000)
这篇关于JavaScript-如何等待/ SetTimeOut /睡眠/延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!