Greetings. Faced a problem in the implementation of a timer with a pause. Pause does not remove the interval, although it should.
function Timer(callback, delay) { var start = new Date().getTime(); var countDownDate = start + delay; var timerId, start, remaining = delay; this.pause = function() { window.clearTimeout(timerId); remaining -= new Date() - start; clearInterval(this.cutdown); }; this.resume = function() { start = new Date(); window.clearTimeout(timerId); timerId = window.setTimeout(callback, remaining); setInterval(this.cutdown, 1000); }; this.cutdown = function() { remaining = remaining - 1000; minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60)); seconds = Math.floor((remaining % (1000 * 60)) / 1000); (remaining < 0) ? clearInterval(this.cutdown) : $("#time").html(minutes + "m " + seconds + "s"); }; this.resume(); } var timer = new Timer(function() { $("#status").html("Stoped"); }, 30000); $("#pause").click(function() { timer.pause(); }); $("#resume").click(function() { timer.resume(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <div id="time"> </div> <div id="status"> Up </div> <div id="pause"> pause </div> <div id="resume"> resume </div> Most likely I messed up with an interval, but I could not understand where.
clearIntervalas well asclearTimeoutaccepts a timer id. and you pass it a function. In turn, you never save the result ofsetInterval(this.cutdown, 1000);which should be passed toclearInterval- Grundy