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

137
Visualizações
js - timespan to use onkeyup

im making a basic 2player RPS game but i cant manage to make the idea workout.

theres a 3second countdown timer, once it ends there has to be a 0.5s timespan to press a button. but i cant figure out or find how to make a timespan..

my current code:

  var p1 = document.getElementById('p1');
var p2 = document.getElementById('p2');
var timer = setInterval(timerFunc, 1000);
var counter = 0;

function timerFunc() { 
    document.getElementById("timer").innerHTML=counter < 3 ? 3 - counter : "";
    if (counter == 3) {

    document.body.onkeyup = function(e){if(e.keyCode == 49){p1.innerHTML = 'scissors';
    }else if(e.keyCode == 50){p1.innerHTML = 'paper';
    }else if(e.keyCode == 51){p1.innerHTML = 'rock';
    }else if(e.keyCode == 56){p2.innerHTML = 'scissors';
    }else if(e.keyCode == 57){p2.innerHTML = 'paper';
    }else if(e.keyCode == 48){p2.innerHTML = 'rock';
  }
}
        clearInterval(timer);
        counter++;
        timer = setTimeout(timerFunc, 500);
        return;
    } else if (counter == 4) {
        clearTimeout(timer);
    }
    counter++;
}

(code has been edited, and i couldnt figure out addeventlisteners for the keyups so i did it with a if else even though it looks super messy)

time span still doesnt work properly

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

0

The game, fully working, with both the 3s countdown and the .5s timespan for click, could look something like this:

const PLAYERS = {
    player1: {
        name: 'Player 1',
        keys: ['q', 'w', 'e'],
        throw: ['scissors', 'rock', 'paper'],
        played: false
    },
    player2: {
        name: 'Player 2',
        keys: ['r', 't', 'y'],
        throw: ['scissors', 'rock', 'paper'],
        played: false
    }
};

const PLAYERS_VALS = Object.values(PLAYERS);

let count = 3;
let countdown = document.querySelector('#countdown');
countdown.innerHTML = count;
let canPlay = false;

const PLAY = key => {
    PLAYERS_VALS.forEach((player, i) => {
        if (player.keys.includes(key) && player.played == false) { // DO WHATEVER ONCE X PLAYER CLICKS
            player.played = true; // PREVENT CHANGING CHOICE
            let idx = player.keys.indexOf(key);
            document.querySelector(`#player${i + 1}`).innerHTML = `${player.name} threw <b>${player.throw[idx]}</b>`;
        }
    });
};

let cntID;
const COUNTDOWN = () => {
    // ADD THE 3 SECONDS COUTDOWN
    cntID = setInterval(() => {
        count--;
        countdown.innerHTML = count;
        if (count === 0) {
            canPlay = true; // ALLOW THE CLICKS
            countdown.innerHTML = 'GO!';
            clearInterval(cntID); // STOP COUNTDOWN ONCE IT REACHES 0

            // ADD THE .5 SECONDS TIMESPAN TO CLICK
            setTimeout(() => {
                canPlay = false; // DISABLE THE CLICKS
                countdown.innerHTML = 'Ended.';
            }, 500);
        }
    }, 1000);
};

COUNTDOWN();

const RESTART = () => {
    count = 3;
    countdown.innerHTML = count;
    PLAYERS_VALS.forEach((player, i) => {
        player.played = false;
        document.querySelector(`#player${i + 1}`).innerHTML = `${player.name}`;
    });
    COUNTDOWN();
};


document.body.addEventListener('keydown', e => {
    if (canPlay) PLAY(e.key);
});

document.querySelector(`#restart`).addEventListener('click', e => {
    RESTART();
});
<div id="countdown"></div>
<div id="player1">Player 1</div>
<div id="player2">Player 2</div>
<button id="restart">Restart</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

var timer = setInterval(timerFunc, 1000);
var counter = 0;

function timerFunc() { 
    document.getElementById("timer").innerHTML=counter < 3 ? 3 - counter : "";
    if (counter == 3) {
        document.body.onkeyup == function() {} // 
        clearInterval(timer);
        counter++;
        timer = setTimeout(timerFunc, 500);
        return;
    } else if (counter == 4) {
        clearTimeout(timer);
    }
    counter++;
}
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