最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Pausing Javascript execution until button press - Stack Overflow

programmeradmin1浏览0评论

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.

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 while loop?

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

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.

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 while loop?

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

Share Improve this question edited Mar 24, 2014 at 23:41 SomeKittens asked Apr 28, 2012 at 18:32 SomeKittensSomeKittens 39.5k19 gold badges115 silver badges145 bronze badges 1
  • no, because window.stop() doesn't stop script execution, it stops window from loading, similar to browser's stop button. – keune Commented Apr 28, 2012 at 18:39
Add a comment  | 

2 Answers 2

Reset to default 13
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

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

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

发布评论

评论列表(0)

  1. 暂无评论