问题
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>
回答1:
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.
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.
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>
来源:https://stackoverflow.com/questions/47692911/is-it-possible-continue-a-stopped-async-function