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";
}
最佳答案
2020 年更新
这可以通过 Promises (ES2015) 和 async/await (ES2017) 轻松实现。
这里我们使用 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
}
The await expression causes async function execution to pause until a Promise is settled, and to resume execution of the async function after fulfilment.
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.
关于javascript - 暂停功能,直到按下回车键javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17176046/