Beren
Beren

Reputation: 744

Is there any Javascript code to detect that no key is pressed?

I am actually doing a go / no go test in which a user have to press spacebar when he see a letter other then "F" and ignores when the letter F appears. But i am having a problem that if the user didn't press the spacebar on the letters other then F ,then it should be gone wrong but i am unable to code that thing

function respondToInput(event) {
    if (event.code != undefined && event.code != 'Space') {
        // Don't record non-spacebar presses
        return;
    } else if (textArea.textContent == 'F') {
        if (event.code === 'Space') {
            alert("You dont have to press the spacebar")
        }
    } else if (textArea.textContent != 'F') {
        if (event.code != 'Space') {
            alert("You have to press the spacebar")
        }
    }
}

Upvotes: 4

Views: 771

Answers (1)

pacukluka
pacukluka

Reputation: 735

You need to set a timer to check if space was pressed between F appearing and some time interval.

That can be done with some code such as this:

let fTimeout = null; //Timer to check if F was pressed
let waitMS = 5000; //5 seconds

function showF(){
    textArea.textContent = 'F';
    fTimeout = setTimeout(()=>{
        alert('You didnt press space in time!');
    }, waitMS);
}

function respondToInput(event) {
    if (event.code != undefined && event.code != 'Space')  
        return; // Discard non space

    if (event.code === 'Space'){
        if(fCheckTime == null) //we arent waiting for space presses, discard
            alert("You dont have to press the spacebar");
        else{
            window.clearTimeout(fTimeout); //cancel timeout
            fTimeout = null;
            alert('Congrats');
        }
    }

}

//Test it out
showF();

Upvotes: 1

Related Questions