[英]pause function until enter key is pressed javascript
javascript 新手。 我知道这可能很简单,但我无法弄清楚。 我想执行一个函数。 在函数中间暂停并等待用户点击“回车”键,这将允许函数再次继续(或将调用另一个函数来触发)。
function appear()
{
document.getElementById("firstt").style.visibility="visible";
//here is where I want the pause to happen until the user presses "enter" key
//Below is what I want to happen after the "enter" key has been pressed.
document.getElementById("startrouter").style.visibility="visible";
}
2020 年更新
这可以通过Promises (ES2015)和async/await (ES2017)轻松实现。
这里我们使用 async/await 来暂停执行并等待 Promise 完成:
async function test() { console.log('waiting keypress..') await waitingKeypress(); console.log('good job!') }
在实用函数中,我们立即返回一个 Promise,但是测试函数中的await等待解析被调用:
function waitingKeypress() { return new Promise((resolve) => { document.addEventListener('keydown', onKeyHandler); function onKeyHandler(e) { if (e.keyCode === 13) { document.removeEventListener('keydown', onKeyHandler); resolve(); } } }); }
奖金回合
使用等待 Promise 的模式,我们还可以编写一个等待 x 秒然后继续执行的函数:
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
这等待 1 秒钟:
async function test() {
await delay(1000);
// Goes on after 1 second
}
await 表达式导致异步函数执行暂停,直到 Promise 被解决,并在完成后恢复异步函数的执行。
Promise 是在创建 Promise 时不一定知道的值的代理。 它允许您将处理程序与异步操作的最终成功值或失败原因相关联。
我会创建一个全局变量来查看 javascript 是否正在等待按键。
在脚本的顶部,您可以添加
var waitingForEnter = false;
然后在您的函数中将其设置为 true
function appear()
{
document.getElementById("firstt").style.visibility="visible";
waitingForEnter = true;
}
然后...为回车键添加一个监听器
function keydownHandler(e) {
if (e.keyCode == 13 && waitingForEnter) { // 13 is the enter key
document.getElementById("startrouter").style.visibility="visible";
waitingForEnter = false; // reset variable
}
}
// register your handler method for the keydown event
if (document.addEventListener) {
document.addEventListener('keydown', keydownHandler, false);
}
else if (document.attachEvent) {
document.attachEvent('onkeydown', keydownHandler);
}
我希望这有帮助。 这只是我会做的,它可能不是最好的方法。
或者我们可以从 Javalsu 内联解决方案,并摆脱全局变量。
function appear(){
document.getElementById("firstt").style.visibility="visible";
//here is where I want the pause to happen until the user presses "enter" key
function after(){
//Below is what I want to happen after the "enter" key has been pressed.
document.getElementById("startrouter").style.visibility="visible";
}
function keydownHandler(e) {
if (e.keyCode == 13 && waitingForEnter) { // 13 is the enter key
after();
}
}
// register your handler method for the keydown event
if (document.addEventListener) {
document.addEventListener('keydown', keydownHandler, false);
}
else if (document.attachEvent) {
document.attachEvent('onkeydown', keydownHandler);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.