繁体   English   中英

在 Javascript 中暂停

[英]Pausing in Javascript

有没有办法在 JS 中暂停代码执行? 我正在尝试创建一个基于浏览器的终端,但在创建用户输入类型功能时遇到了问题。

本质上,我想要一个名为 currentCommand 的参数,它在错误的 state 和一个 function 中初始化,它等待 currentCommand 变量在完成之前更改:

 while(;currentCommand) { pass; }

这是我希望它的应用方式:

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

上下文的示例实现: https://jsfiddle.net/u98r1dyp/17/#&togetherjs=jmnaRa89uT

您可能得到的最接近的方法是承诺您正在使用的 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`); })();

(另请注意,您需要另一个)addEventListener的末尾,并且您可能想拼写正确的answer - asnwer从未定义)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM