gpt4 book ai didi

javascript - 如何运行函数,当用户没有在特定时间 JS 进行输入时

转载 作者:行者123 更新时间:2023-12-04 14:06:05 25 4
gpt4 key购买 nike

我正在写心理测验,我会用它来测试人的能力。

我正在寻找解决方案。用户必须在 1 秒内完成输入,否则应跳过该问题。

功能:

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

总的来说,我尝试了几种方法但都失败了。

编辑:基于 majusebetter 答案,我实现了 setTimeout。代码:

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);
}
});
});
}

最佳答案

该问题的一个简单解决方案是将 setTimeout()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/

关于javascript - 如何运行函数,当用户没有在特定时间 JS 进行输入时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68454309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com