How to run function, when user does not make an input in specyfic time JS

Viewed 59

Im currently writing the psychological test, which I will use to test people's abilities.

I'm looking for solution. User has to make an input in 1s, otherwise the question should be skipped.

Function:

  return new Promise((resolve) => {
    document.addEventListener("keydown", (event) => {
      if (event.key === "a") {
        resolve(true);
      }
    });
  });
}

In general I tried few approaches and failed.

Edit: Based on majusebetter answer I implement setTimeout. Code:

async function waitForClue() {
  return new Promise((resolve) => {
    const waitForAnswer = () =>
      setTimeout(() => {
        resolve("no answer");
        clearTimeout(waitForAnswer);
      }, 1000);
    waitForAnswer();
    document.addEventListener("keydown", (event) => {
      if (event.key === "a") {
        resolve(true);
      }
    });
  });
}

2 Answers

A simple solution to that problem could be the usage of setTimeout() in combination with clearTimeout().

function nextQuestion() {
  // Do your "skip" stuff here
  alert('Too late!');
}


const input = document.getElementById('answer');
input.focus();

const handle = window.setTimeout(() => nextQuestion(), 2000);
input.addEventListener('keydown', event => window.clearTimeout(handle));
<input id="answer" type="text">

https://jsfiddle.net/0ymn65ok/1/

Using promises

const race = () => new promise((resolve, reject) => {
   setTimeout(reject, 1000)
   input.addEventListener('keydown', resolve);
});

race().then(() => console.log("success")).catch(() => console.log("fail"));
Related