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

169
Visualizações
How to end setTimeout after user input

Im developing a game in JavaScript in which the user needs to give a key input (press spacebar) when a clock hand moves slightly more than usual. Currently, I am using a setTimeout function that gives the user 1 second to give a key input after the clock hand has ticked (rotated by 10 degrees). If the user correctly presses space when the clock hand moves more than usual (15 degrees), an indicator will flash green, otherwise it will flash red.

The problem I am running into is that once the user gives an input within 1 second of the hand moving, the indicator will not flash until AFTER that 1 second has passed (ie, if the user gives an input after 0.4 seconds, the indicator will not flash until 0.6 later)

I know this is because the indicator is set up in my setTimeout fuction, which will only execute the code after 1 second. I have tried to test for the user input outside of the setTimeout function but that way the user does not get 1 second to give a response.

I was wondering if there is a way around this problem or a better way to approach this?

//Get input after clock tick

setTimeout(() => {
    if (irregular_tick && space_pressed) {
        flashScreenGreen();
    }
    if (!(space_pressed) && irregular_tick) {
        flashScreenRed();
    }             
},1000);

Thanks for any help!

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

0

You'll need to keep a reference to your timer outside of the setTimeout callback and add a listener for the keypress with an interrupt callback which will clear the timeout if all conditions are met.

let timer = null;
let space_pressed = false;

function reset() {
  timer = null;
  space_pressed = false;
}

function interruptHandler(e) {
  if (timer !== null) { // only look for spacebar if timer is running
    space_pressed = e.key === ' ';

    if (irregular_tick && space_pressed) {
      // clear timeOut if successful
      clearTimeout(timer);
      reset();

      flashScreenGreen();
    }
  }
}

document.body.addEventListener('keyup', interruptHandler);

timer = setTimeout(() => {
  if (!space_pressed && irregular_tick) {
    flashScreenRed();
  }

  // reset timer at end of callback ready for next run
  reset();
}, 1000);

As a side note it looks like you've defined two separate flashScreenGreen() and flashScreenRed() functions. I'm guessing that they have similar if not identical logic. If that is the case you might want to consider defining a single utility flashScreen() function which accepts a color as a parameter.

function flashScreen(color) {
  // logic utilizing 'color'
}

// usage
flashScreen('green');
flashScreen('#FF0000'); // red as hex
about 4 years ago · Juan Pablo Isaza Relatório

0

I think the clearTimeout function will help you here

   // Hold the reference to the timer
    const timeoutId = setTimeout(() => {
    if (irregular_tick && space_pressed) {
        flashScreenGreen();
        //You can use the clearTimeout function to end the timer
        clearTimeout(timeoutId);
    }
    if (!(space_pressed) && irregular_tick) {
        flashScreenRed();
        //clear timeout, if you need it here too
        clearTimeout(timeoutId);
    }             
},1000);
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