Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
La declaración se omite cuando se ejecuta en Javascript

Quiero crear un mini juego de piedra, papel o tijera simple y rápido. Cómo funciona es que cuando el usuario hace clic en el botón INICIAR JUEGO, le da al usuario un elemento aleatorio, por ejemplo , "rock" . Cuando el usuario recibe el artículo, la identificación "computer-item" debería mostrarse:

"Equipo: Procesando salida..."

Después de 3 segundos, muestra el elemento aleatorio de la computadora, por ejemplo , papel . Este problema se encuentra en la función startGame() . ¿Cómo hago para que esto sea así?

Intenté usar setTimeout para que, con suerte, se mostrara después de 3 segundos. Cualquier ayuda sería muy apreciada ya que soy un poco nuevo en JavaScript.

JavaScript:

 let p_item = document.getElementById("player-item"); let cpu_item = document.getElementById("computer-item"); let items = ["Rock", "Paper", "Scissors"]; function getPlayerHand() { //for (i = 0; i < items.length; i++) let p_index = Math.floor(Math.random() * 3); return items[p_index]; } function getCPUHand() { //for (i = 0; i < items.length; i++) let cpu_index = Math.floor(Math.random() * 3); return items[cpu_index]; } function startGame() { p_item.textContent = "Player: " + getPlayerHand(); cpu_item.textContent = "Computer: Processing output..."; setTimeout(getCPUHand, 3000); cpu_item.textContent = "Computer: " + getCPUHand(); } function playAgain() { clearTimeout(getCPUHand); p_item.textContent = "Player: "; cpu_item.textContent = "Computer: "; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="player-item">Player:</p> <p id="computer-item">Computer:</p> <button onclick="startGame()">START GAME</button> <p>GAME HAS FINISHED <button onclick="playAgain()">PLAY AGAIN</button> </p> <script src="index.js"></script> </body> </html>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Está llamando a setTimeout, pero el script ejecuta la siguiente línea inmediatamente, lo que ya establece el valor. Puedes probar esto y ver si funciona:

 function startGame() { p_item.textContent = "Player: " + getPlayerHand(); cpu_item.textContent = "Computer: Processing output..."; setTimeout(() => { cpu_item.textContent = "Computer: " + getCPUHand(); }, 3000); }
about 4 years ago · Juan Pablo Isaza Relatório

0

setTimeout() ejecuta getCPUHand() 3 segundos después, pero no lo espera. Regresa inmediatamente, y luego la línea cpu_item.textContent = "Computer: " + getCPUHand(); carreras. Debe poner el código que muestra la mano de la computadora en la llamada setTimeout() .

El argumento de clearTimeout() debe ser el valor devuelto por setTimeout() . Así que asigna ese valor a una variable global, que usas cuando reinicias.

 let p_item = document.getElementById("player-item"); let cpu_item = document.getElementById("computer-item"); let items = ["Rock", "Paper", "Scissors"]; let timer; function getPlayerHand() { //for (i = 0; i < items.length; i++) let p_index = Math.floor(Math.random() * 3); return items[p_index]; } function getCPUHand() { //for (i = 0; i < items.length; i++) let cpu_index = Math.floor(Math.random() * 3); return items[cpu_index]; } function startGame() { p_item.textContent = "Player: " + getPlayerHand(); cpu_item.textContent = "Computer: Processing output..."; timer = setTimeout(() => cpu_item.textContent = "Computer: " + getCPUHand(), 3000); } function playAgain() { clearTimeout(timer); p_item.textContent = "Player: "; cpu_item.textContent = "Computer: "; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="player-item">Player:</p> <p id="computer-item">Computer:</p> <button onclick="startGame()">START GAME</button> <p>GAME HAS FINISHED <button onclick="playAgain()">PLAY AGAIN</button> </p> <script src="index.js"></script> </body> </html>

about 4 years ago · Juan Pablo Isaza Relatório

0

 let p_item = document.getElementById("player-item"); let cpu_item = document.getElementById("computer-item"); let items = ["Rock", "Paper", "Scissors"]; let timeoutHandler = null; function getPlayerHand() { //for (i = 0; i < items.length; i++) let p_index = Math.floor(Math.random() * 3); return items[p_index]; } function getCPUHand() { //for (i = 0; i < items.length; i++) let cpu_index = Math.floor(Math.random() * 3); return items[cpu_index]; } function startGame() { p_item.textContent = "Player: " + getPlayerHand(); cpu_item.textContent = "Computer: Processing output..."; timeoutHandler = setTimeout(()=>{ getCPUHand(); cpu_item.textContent = "Computer: " + getCPUHand(); }, 3000); } function playAgain() { clearTimeout(timeoutHandler ); p_item.textContent = "Player: "; cpu_item.textContent = "Computer: "; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="player-item">Player:</p> <p id="computer-item">Computer:</p> <button onclick="startGame()">START GAME</button> <p>GAME HAS FINISHED <button onclick="playAgain()">PLAY AGAIN</button> </p> <script src="index.js"></script> </body> </html>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda