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

107
Visualizações
Javascript Event Listener when nothing is happening after a period of time

I would ask if someone know an Event Listener, that start to work when there aren't pressed button on the Keyboard for a determined period of time, something like that:

document.addEventListener('wait', myFunction);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use setTimeout and clearTimeout for this.

setTimeout runs a function after a specified period of time. It also returns an ID that can be passed to clearTimeout.

clearTimeout cancels the timeout associated with the ID that you give it.

You would call setTimeout to start the "idle timer", and store the timer ID in a variable. Then, if the user pressed a key (which you could detect using a keypress event listener) then you would use clearTimeout to cancel the timer (and maybe start it again).

about 4 years ago · Juan Pablo Isaza Relatório

0

You can find useful answer here : How to detect idle time in JavaScript

You would use the 'keypress' event. So basically create a timeout and reset it every time a key is pressed!

Hope it helps!

about 4 years ago · Juan Pablo Isaza Relatório

0

There isn't a listener that will do that. So perhaps:

  1. Set up a status variable that is reset when a key is pressed.

  2. Create a delay function. In this example I'm returning a promise from the function that can be awaited.

  3. When main is called it awaits the delay promise to be resolved. If no key has been pressed it calls a function and awaits for it to complete, then calls main again, otherwise no further action is taken.

// Cache the output element used in `writer`
const output = document.querySelector('.output');

// Initialise the status
let status = false;

// Check for `keypress` events
document.addEventListener('keypress', () => status = true);

// Accepts an argument specifying how
// many milliseconds delay there will be
function delay(n) {
  return new Promise(res => {
    setTimeout(() => res(), n);
  });
}

// Random function to test the delay works
function writer() {
  return new Promise(async res => {
    const str = 'Hello world!';
    for (let i = 0; i <= str.length; i++) {
      await delay(250);
      output.textContent = str.substr(0, i);
    }
    res();
  });
}

// Wait 3 seconds. If no key has been pressed
// call the `writer` function. Reset the status, and
// call `main` again
async function main() {

  await delay(3000);

  if (!status) {
    console.log('No key pressed - calling writer()');
    await writer();
  } else {
    console.log('Key pressed - no further action');
  }

  status = false;
  main();

}

main();
<div class="output"></div>

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