Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda