是否可以继续停止异步功能? [英] Is it possible continue a stopped async function?

查看:107
本文介绍了是否可以继续停止异步功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解promises,我想知道如何启动和停止异步函数,就像我的示例show。当你点击按钮时,它从开始和停止开始,但似乎无法继续。

I'm trying to learn about promises, and I wonder about to start and stop an async function, like my example show. It starts at the begining and stop when you click the button, but it seems can't continue.

var stop = 0;
var elParrafo = document.getElementById('miParrafo');

function sendStop() {
  stop = 1;
}

function sendStart() {
  stop = 0;
}

function esperar(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, ms)
  });
}

async function trabajar() {
  while (stop === 0) {
    elParrafo.innerHTML += " > ";
    await esperar(50);
  }
}

trabajar();

<form class="" action="index.html" method="post">
  <input type="button" value="Stop" onclick="sendStop()">
  <input type="button" value="Start" onclick="sendStart()">
</form>
<p id="miParrafo"></p>

推荐答案

停止/重新启动和暂停之间存在差异。您正在描述要暂停和继续的功能。

There is a difference between stopping/restarting and pausing. You are describing the feature to pause and to continue.

如果您希望暂停/继续,则需要循环以继续运行并添加内部条件以检查您当前是否暂停。

If you wish to pause/continue you need the while loop to keep running and add an internal condition to check if you are currently paused or not.

您当然可以重新调用 trabajar( ); 重新启动但重新启动并继续在逻辑上是2个不同的东西,重启可能想要清除现有输出,而继续没有。

You could off course just re-call trabajar(); to restart but restarting and continuing is logically 2 different things and a restart might want to clear the existing output while continue does not.

可能有很多方法可以做到这一点,但最快的演示暂停/继续以及停止/重启可以完成类似于下面的操作。再次,可以随意重新调用 trabajar(); 但这取决于你。

There is probably many ways to do this but the quickest to demonstrate pause/continue as well as stop/restart can be done similar to the below. Again, feel free to just re-call trabajar(); but that is up to you.

var stop = false;
var pause = false;
var elParrafo = document.getElementById('miParrafo');

function sendPause() {
  pause = true;
}

function sendContinue() {
  pause = false;
}

function sendStop() {
  stop = true;
}

function sendRestart() {
  sendStop();
  setTimeout(function() {
    stop = false;
    pause = false;
    elParrafo.innerHTML = "";
    trabajar();
  }, 50)
}

function esperar(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, ms)
  });
}

async function trabajar() {
  while (!stop) {
    if (!pause) {
      elParrafo.innerHTML += " > ";
    }
    await esperar(50);
  }
}

trabajar();

<form class="" action="index.html" method="post">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
  <input type="button" value="Restart" onclick="sendRestart()">
</form>
<p id="miParrafo"></p>

这篇关于是否可以继续停止异步功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆