Is there a convenient way to interrupt setInterval for a certain time without freezing the page? It is important to continue executing setInterval later.

  • 2
    clearInterval(timer); and again timer = setInterval(...); - Igor
  • Well yes. Abort setInterval and run it again later. - Drakonoved

1 answer 1

As already answered in the comments - you can remove the interval, and re-set. This is the easiest and most reasonable way to temporarily interrupt its implementation.

But if it is necessary to pause the interval (to subsequently continue from the time of the last reference) - this is an example of solving such a problem:

 var itrEl = document.getElementById('iterations'), tfsEl = document.getElementById('time-from-start'), pauseBtn = document.getElementById('pause'), interval; interval = new RAFInterval(() => { itrEl.textContent = +itrEl.textContent + 1; }, 5000); interval.ontick = t => tfsEl.textContent = (t / 1000).toFixed(2); pauseBtn.addEventListener('click', function () { if (interval.togglePause()) this.textContent = 'Продолжить'; else this.textContent = 'Приостановить'; }); interval.start(); function RAFInterval(func, delay, run = false) { let rqst, tStart, tLast, tIter, paused = false; tStart = tLast = tIter = 0; this.delay = delay; this.ontick = null; let fr = time => { tLast = time; if (!paused) { tIter = time - tStart; if (this.ontick) this.ontick(tIter); if (tIter > delay) { func(); tStart = time; } } rqst = requestAnimationFrame(fr); }; this.togglePause = () => { if (!(paused = !paused)) tStart = tLast - tIter; return paused; }; this.start = () => fr(); this.stop = () => cancelAnimationFrame(rqst); if (run) this.start(); } 
 Выполнено итераций: <span id="iterations">0</span><br> Отсчет задержки: <span id="time-from-start">0</span>c<br> <br> <button id="pause">Приостановить</button> 

requestAnimationFrame has a plus: in situations where classic timers “slow down” because of the desire of the browser to get maximum responsiveness - it works smoothly. Of course, its minimum resolution is ~ 15..20ms, but I haven’t yet met any problems where most accuracy was really needed :)