Skip to content Skip to sidebar Skip to footer

Pausing Javascript Execution Until Button Press

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. Curre

Solution 1:

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

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

Live DEMO

Solution 2:

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

functiondoStuff() {
  // 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);
}

functionnext() {
  if (!paused) {
    doStuff();
  }
}

doStuff();

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

Post a Comment for "Pausing Javascript Execution Until Button Press"