I have made a simple rock paper scissors game with Javascript, I would like to have a delay before the result appears, I have tried seTimeout()
in numerous different ways but cant get it to work.
Here is my Javascript
function game(opt) {
var comp = Math.random();
var pers = opt.value;
if (comp < 0.33) {
comp = "rock"
} else if (comp < 0.66) {
comp = "paper"
} else {
comp = "scissors"
}
if (comp == pers) {
document.getElementById("answer").innerHTML = "Draw, I chose: <b>" + comp+"</b>";
} else if (pers == "rock" && comp == "scissors" || pers == "paper" && comp == "rock" || pers == "scissors" && comp == "paper") {
document.getElementById("answer").innerHTML = "Well done you won, I chose: <b>" + comp+"</b>";
} else if (pers == "rock" && comp == "paper" || pers == "paper" && comp == "scissors" || pers == "scissors" && comp == "rock") {
document.getElementById("answer").innerHTML = "Sorry you lose, I chose: <b>" + comp+"</b>";
}
document.getElementById("info").innerHTML = pers+" V "+comp;
};
Here is my HTML
<body>
<div id="alignCenter">
<h1 onclick="rock()" align="center">Rock, Paper, Scissors...</h1>
<h2 align="center">Pick one</h2>
<div id="images">
<button value="rock" id="rock" onclick="game(rock)"> <img src="images/rock.gif" alt="rock" onclick="rock()" width="196" height="144"> </button>
<button value="paper" id="paper" onclick="game(paper)"> <img src="images/paper.png" alt="paper" onclick="paper()" width="196" height="263"> </button>
<button value="scissors" id="scissors" onclick="game(scissors)"> <img src="images/scissors.png" alt="scissors" width="196" height="200"> </button>
</div>
<div align="center" id="answer">
</div>
The game works perfect I would just like there to be a delay, Also if it is possible during the delay is there away to make it flash: "rock" then flash "paper" then flash "scissors" for about a second each, How would I do this?
Thanks in advance :)
Wrap the middle part in a setTimeout
function. I also added one line of code right before the setTimeout function so that it would clear the previous answer while waiting for the new result.
document.getElementById("answer").innerHTML = "";
setTimeout(function(){
if (comp == pers) {
document.getElementById("answer").innerHTML = "Draw, I chose: <b>" + comp+"</b>";
} else if (pers == "rock" && comp == "scissors" || pers == "paper" && comp == "rock" || pers == "scissors" && comp == "paper") {
document.getElementById("answer").innerHTML = "Well done you won, I chose: <b>" + comp+"</b>";
} else if (pers == "rock" && comp == "paper" || pers == "paper" && comp == "scissors" || pers == "scissors" && comp == "rock") {
document.getElementById("answer").innerHTML = "Sorry you lose, I chose: <b>" + comp+"</b>";
}
},1000);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.