不久前我用 C# 构建了一个 C 解释器,现在已经开始将其转换为 Javascript。一切都很顺利,直到我意识到 js 没有睡眠功能。我的解释器使用递归解析器,当它嵌套多个函数时,它会暂停用户输入(在 C# 中,我在第二个线程中使用了等待句柄)。我看过 setInterval 和 setTimeout 但它们是异步/非阻塞的;当然,busywait 是不可能的,我查看了我在 SO 上找到的 timed_queue 实现,但没有运气。我在主窗口和网络工作者中都尝试过解析器。我正在使用 jQuery。我对 js 的经验有限,正在寻找可以追求的想法。我对连续传球风格或收益率知之甚少,我想知道他们是否可能掌握关键。这里是从代码中删减的部分,以显示一些控制脚本。请有任何想法。
var STATE = {
START: "START",
RUN: "RUN", //take continuous steps at waitTime delay
STEP: "STEP", //take 1 step
PAUSE: "PAUSE",//wait for next step command
STOP: "STOP",
ERROR: "ERROR"
}
var state = state.STOP;
function parsing_process() //long process we may want to pause or wait in
{
while(token !== end_of_file)//
{
//do lots of stuff - much of it recursive
//the call to getNextToken will be encountered a lot in the recursion
getNextToken();
if (state === STATE.STOP)
break;
}
}
function getNextToken()
{
//retrieve next token from lexer array
if (token === end_of_line)
{
//tell the gui to highlight the current line
if (state === STATE.STOP)
return;
if (state === STATE.STEP)//wait for next step
{
//mimick wait for user input by using annoying alert
alert("click me to continue")
}
if (state === STATE.RUN) {
//a delay here - set by a slider in the window
//a busy wait haults processing of the window
}
}
}
我已经使用 task.js 让它在 Firefox 中工作
<html>
<head>
<title>task.js examples: sleep</title>
<script type="application/javascript" src="task.js"></script>
</head>
<body>
Only works in FIREFOX
<button onclick="step()">Step</button>
<button onclick="run()">Run</button>
<button onclick="stop()">Stop</button>
<pre style="border: solid 1px black; width: 300px; height: 200px;" id="out">
</pre>
<script type="application/javascript;version=1.8">
function start() {
process();
}
function step() {
if (state === STATE.STOP)
start();
state = STATE.STEP;
}
function run() {
if (state === STATE.STOP)
start();
state = STATE.RUN;
}
function stop() {
state = STATE.STOP;
}
var STATE = {
START: "START",
RUN: "RUN", //take continuous steps at sleepTime delay
STEP: "STEP", //take 1 step
PAUSE: "PAUSE",//wait for next step command
STOP: "STOP",
ERROR: "ERROR"
}
var state = STATE.STOP;
var sleepTime = 500;
function process() {
var { spawn, choose, sleep } = task;
var out = document.getElementById("out");
var i=0;
out.innerHTML = "i="+i;
var sp = spawn(function() {
while(state !== STATE.STOP)
{
i++;
out.innerHTML = "i="+i;
if (state === STATE.RUN)
{
yield sleep(sleepTime);
}
if (state === STATE.STEP)
state = STATE.PAUSE;
while (state===STATE.PAUSE)
{
yield;
}
}
});
}
</script>
</body>
</html>
如果知道有关承诺的人能给我更多线索,我将不胜感激。我的应用程序不是消费者应用程序,但如果它运行在 Firefox 之外就更好了