我正在为我的Algorithms类(在Javascript中)创建一个Sudoku创建器的可视化。该算法运行良好,但我找不到暂停执行的方法。
目前,我正在使用prompt()
暂停,但这是笨重和烦人的。除了连续的while
循环之外,还有什么方法可以暂停直到运行另一个函数(通过HTML按钮)?
我可以发布代码,但我认为不需要。我目前没有使用jQuery,但如果需要我可以。
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!!!" />
如果你试图暂停的是一个本来会循环的函数,我会想出一个很好的解决方案:
HTML
<div id="stuff">Doing stuff</div>
<button id="pause">Pause/Resume</button>
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();