Suspend Javascript Execution Until Button Clicked

I am creating a Sudoku creator visualization for my Algorithms class (in Javascript). The algorithm works fine, but it's hard for me to find a way to pause execution.

I am currently using prompt() to pause, but this is cumbersome and annoying. Is there a way to pause until another function is started (via the HTML button), except for a continuous while ?

I can post the code, but I don't think it is needed. I am not currently using jQuery, but I can if necessary.

+6
source share
2 answers
 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

+8
source

If what you are trying to pause is a function that would otherwise maintain a loop, I came 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
source

Source: https://habr.com/ru/post/914423/


All Articles