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
source share