暂停 Javascript 执行直到按下按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10366387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:37:34  来源:igfitidea点击:

Pausing Javascript execution until button press

javascripthtml

提问by SomeKittens

I'm creating a visualization of a Sudoku creator for my Algorithms class (in Javascript). The algorithm works great, but I'm having trouble finding a way to pause execution.

我正在为我的算法类(在 Javascript 中)创建数独创建者的可视化。该算法效果很好,但我无法找到暂停执行的方法。

Currently, I'm using prompt()to pause, but that's bulky and annoying. Is there any way to pause until another function is run (via HTML button) other than a continuous whileloop?

目前,我正在使用prompt()暂停,但这既笨重又烦人。除了连续while循环之外,是否有任何方法可以暂停,直到运行另一个功能(通过 HTML 按钮)?

I can post code, but I don't think it's needed. I'm not currently using jQuery, but I can if needed.

我可以发布代码,但我认为不需要。我目前没有使用 jQuery,但如果需要我可以。

回答by gdoron is supporting Monica

var flag = true;
function foo(){
    if (flag){
        // Do your magic here
        ...
        ...
        setTimeout(foo, 100);
    }
}

function stop(){
    flag = false;
}
<input type="button" onclick="stop();" value="stop it!!!" />

Live DEMO

现场演示

回答by Liran H

If what you are trying to pause is a function which would otherwise keep looping, I've come up with a good solution:

如果您要暂停的是一个会继续循环的函数,我想出了一个很好的解决方案:

HTML

HTML

<div id="stuff">Doing stuff</div>
<button id="pause">Pause/Resume</button>

JS

JS

var paused = false;

document.getElementById('pause').addEventListener('click', function() {
  paused = !paused;
  if (!paused) {
    next();
  }
});

function doStuff() {
  // Do whatever you want here, then invoke next() for the next iteration of that function, for example:
  // (Note that the window.setTimeout is NOT part of the solution)
  window.setTimeout(function() {
    document.getElementById('stuff').append('.');
    next();
  }, 300);
}

function next() {
  if (!paused) {
    doStuff();
  }
}

doStuff();

CodePen:https://codepen.io/liranh85/pen/baVqzY?editors=1010

CodePen:https ://codepen.io/liranh85/pen/baVqzY ? editors = 1010