[英]Pausing in Javascript
Is there a way to pause code execution in JS?有没有办法在 JS 中暂停代码执行? I'm trying to create a browser based terminal, and I'm having trouble creating a user input type functionality.我正在尝试创建一个基于浏览器的终端,但在创建用户输入类型功能时遇到了问题。
Essentially I want to have a parameter called currentCommand which initializes in a false state and a function which waits for the currentCommand variable to change before completing like:本质上,我想要一个名为 currentCommand 的参数,它在错误的 state 和一个 function 中初始化,它等待 currentCommand 变量在完成之前更改:
while(;currentCommand) { pass; }
Here's how I'd like it to be applied:这是我希望它的应用方式:
let currentCommand = false; // this variable holds the command the user has entered // Placeholder of a user text input document.addEventListener('keydown', () => { currentCommand = 'Timmy'; } // Problematic function function getAnswer(){ currentCommand = false; // something that will pause the function while currentCommand is false return currentCommand } // Example of implementation console.log('Hi what is your name?'); let answer = getAnswer(); console.log(`${asnwer}, that's a silly name`);
An example implementation for context: https://jsfiddle.net/u98r1dyp/17/#&togetherjs=jmnaRa89uT上下文的示例实现: https://jsfiddle.net/u98r1dyp/17/#&togetherjs=jmnaRa89uT
The closest you can probably get would be to promisify whichever API you're using and await
its resolution:您可能得到的最接近的方法是承诺您正在使用的 API 并await
其解决:
const getAnswer = () => new Promise((resolve) => { document.addEventListener('keydown', () => { resolve('Timmy'); }); }); (async () => { console.log('Hi what is your name?'); const answer = await getAnswer(); console.log(`${answer}, that's a silly name`); })();
(also note that you need another )
at the end of addEventListener
, and you probably want to spell answer
right - asnwer
is never defined) (另请注意,您需要另一个)
在addEventListener
的末尾,并且您可能想拼写正确的answer
- asnwer
从未定义)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.