2012-04-28 53 views
6

我正在为我的算法类(使用Javascript)创建一个Sudoku创建器的可视化。该算法效果很好,但我无法找到暂停执行的方法。暂停Javascript执行,直到按下按钮

目前,我使用prompt()暂停,但这是庞大而烦人的。除了连续的while循环以外,是否有任何方法可以暂停,直到另一个函数运行(通过HTML按钮)?

我可以发布代码,但我不认为这是必要的。我目前不使用jQuery,但如果需要,我可以。

+0

没有,因为'window.stop()'不停止执行脚本,它加载,类似于浏览器的停止按钮停止窗口。 – keune 2012-04-28 18:39:43

回答

8
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!!!" /> 

+1

我试图避免在后台启动'while()'循环。有没有其他方法? (如果没有,这看起来不错) – SomeKittens 2012-04-28 18:37:45

+2

你的意思是'setTimeout(foo)',而不是'setTimeout(flag)'。 – DCoder 2012-04-28 18:39:43

+0

@DCoder。是的,一分钟前解决了。谢谢。 – gdoron 2012-04-28 18:43:10

0

如果你正在尝试暂停的,否则一直循环的功能,我想出了一个很好的解决方案:

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(); 

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