JavaScript暂停功能直到按下回车键

6

刚接触 JavaScript。我知道这可能很简单,但我想不出来。我想执行一个函数,在函数中间暂停并等待用户按下“Enter”键,然后函数将再次继续(或调用另一个函数触发)。

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";


}

做不到。抱歉。 - John Dvorak
可以做到。只是不能在一个方法中完成。您需要将此函数分成几个部分,并使延迟的代码从“Enter”键按下的事件处理程序中执行。 - Nick Roth
1
@NickRoth 是的。不过,那并不是“暂停一个方法”;-) - John Dvorak
有点相关:https://dev59.com/RGYq5IYBdhLWcg3wwDRA - John Dvorak
3个回答

13

更新2020

这可以很容易地通过Promises(ES2015)async/await(ES2017)实现。

  1. 在这里,我们使用async/await暂停执行并等待Promise被完成:

async function test() {
  console.log('waiting keypress..')
  await waitingKeypress();
  console.log('good job!')
}
在实用函数中,我们立即返回一个Promise,但是来自测试函数的await会等待resolve被调用:
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
}

MDN的await

await表达式会导致异步函数的执行暂停,直到Promise完成并返回结果后,才会继续执行异步函数。

MDN的Promise

Promise是一个代理对象,它代表了一个在创建Promise时未必已知的值,能够让你为一个异步操作的成功值或失败原因关联回调函数。


3

我会创建一个全局变量,以查看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);
}

希望这可以帮到你。这只是我会做的事情,可能不是最好的方法。


2
你似乎并没有真正使用 waitingForEnter - John Dvorak
1
是的,我宁愿使用jQuery进行处理程序绑定 :-) - John Dvorak
4
我很愿意帮忙翻译,原文的意思是“我也希望如此,但是没有“jquery”标签。 回答要求使用javascript。”,我的翻译是“我也想这样做,但是没有“jquery”标签。问题要求用javascript回答。” - Smeegs

1
或者我们可以内联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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接