如何使此函数异步?或者有更好的解决方案。

huangapple go评论52阅读模式
英文:

How can I make this function asynchronous? Or an even better solution

问题

I understand you'd like a translation of the provided content, excluding the code. Here's the translation:

所以,我正在用JS在控制台内制作一个虚拟操作系统游戏。为了加载操作系统,我有一个旋转加载函数,我现在将展示。

我是一个初学者,我在这个函数中遇到了问题。我目前处于测试阶段,所以在这个函数完成后,我会在控制台中记录"OS Started!",但实际上它同时记录了加载和"OS Started!"。我认为setTimeout会使它暂停直到完成,但实际上并没有。我该怎么解决这个问题?

当我尝试解决这个问题时,首先想到的是使用async,但正如我所说,我是一个初学者,我从未真正学会如何使用async...所以如果你能教我如何使用它或者有更好的解决方案,请告诉我。

英文:

So, I am making a fake operating system game inside the console in JS. And to load the OS I have a twirly loading function which I'll show now.

function OSLoad(OS = "", loadingTimeSeconds = 10) {
  var twirlTimer = (function () {
    var P = ["\\", "|", "/", "-"];
    var x = 0;
    return setInterval(function () {
      process.stdout.write(
        "\r" + P[x++] + " Loading " + OS
      );
      x &= 3;
    }, 250);
  })();

  setTimeout(() => clearInterval(twirlTimer), loadingTimeSeconds + "000");
}

I'm kind of a beginner, and I've ran into a problem with this function. I'm currently in the testing phase, so after this function is done I log to the console "OS Started!", but instead it logs the loading and "OS Started!" at the same time. I assumed that setTimeout would make it pause until it's done, which it didn't. What can I do to solve this?

The first thing that came to mind when I tried to solve this was using async, but as I said, I'm a beginner, and I never actually learned how to use async... So if you could teach me how to use that or an even better solution please do.

答案1

得分: 1

The best way in JS to make code in JS look sync is using async / await.

Instead of using multiple setTimeout, intervals, etc., you can create a simple Promise sleep function and then use this with await.

Below is a simple example. Most of the code is to emulate the console.

// Very simple console emulator
const pre = document.querySelector('pre');
const consoleBuffer = new Array(10).fill(' ');
let cpos = 0;
const consoleWrite = txt => {
  const s = txt.split('');
  for (const c of s) {
    if (c === '\r') cpos = 0;
    else consoleBuffer[cpos++] = c;
  }
  pre.innerText = consoleBuffer.join('');
}
window.process = { stdout: { write: consoleWrite } };

// OS Loader
const sleep = ms => new Promise(r => { setTimeout(r, ms); });

async function OSLoad(OS = "", loadingTimeSeconds = 10) {
  var P = ["\\", "|", "/", "-"];
  var x = 0;
  for (let lp = 0; lp < loadingTimeSeconds * 4; lp++) {
    process.stdout.write(
      "\r" + P[x++] + " Loading " + OS
    );
    x &= 3;
    await sleep(250);
  }
  process.stdout.write("\r" + OS + " is loaded..");
}

OSLoad('Fake OS 4.01');
pre {
  height: 90vh;
  background-color: black;
  color: white;
}
<pre>
</pre>

This code example demonstrates how to create a console emulator and load a fake operating system using async/await and a sleep function.

英文:

The best way in JS to make code in JS look sync is using async / await.

Instead of using multiple setTimeout , intervals etc, your can create a simple Promise sleep function and then use this with await.

Below is a simple example. Most the code is to emulate the console.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

//very simple console emulator
const pre = document.querySelector(&#39;pre&#39;);
const consoleBuffer = new Array(10).fill(&#39; &#39;);
let cpos = 0;
const consoleWrite = txt =&gt; {
  const s = txt.split(&#39;&#39;);
  for (const c of s) {
    if (c === &#39;\r&#39;) cpos = 0;
    else consoleBuffer[cpos++] = c;
  }
  pre.innerText = consoleBuffer.join(&#39;&#39;);
}
window.process = { stdout: { write: consoleWrite } };


//OS Loader
const sleep = ms =&gt; new Promise(r =&gt; { setTimeout(r, ms);});

async function OSLoad(OS = &quot;&quot;, loadingTimeSeconds = 10) {
  var P = [&quot;\\&quot;, &quot;|&quot;, &quot;/&quot;, &quot;-&quot;];
  var x = 0;
  for (let lp = 0; lp &lt; loadingTimeSeconds * 4; lp ++) {
    process.stdout.write(
      &quot;\r&quot; + P[x++] + &quot; Loading &quot; + OS
    );
    x &amp;= 3;
    await sleep(250);
  }
  process.stdout.write(&quot;\r&quot; + OS + &quot; is loaded..&quot;);
}


OSLoad(&#39;Fake OS 4.01&#39;);

<!-- language: lang-css -->

pre {
  height: 90vh;
  background-color: black;
  color: white;
}

<!-- language: lang-html -->

&lt;pre&gt;
&lt;/pre&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月30日 02:03:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定