[英]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.我实际上正在做一个go / no go 测试,其中用户在看到“F”以外的字母时必须按空格键,而在字母 F 出现时忽略。 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但我有一个问题,如果用户没有按 F 以外的字母上的空格键,那么它应该出错了,但我无法编写那个东西
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")
}
}
}
You need to set a timer to check if space was pressed between F appearing and some time interval.您需要设置一个计时器来检查 F 出现和某个时间间隔之间是否按下了空格。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.