Q
Q
qo_0p2015-10-27 16:34:26
JavaScript
qo_0p, 2015-10-27 16:34:26

How to start setInterval from the same place?

I have a 3 second looping animation, by pressing pause for example at the 2nd second and then starting, my animation continues where it left off, but the remaining 1 second stretch is extended by 3 seconds. How to make the timer "play out" the remaining period of time, and then "play" a full cycle?

function Pause() {
  if (!paused){
    clearInterval(timer);
    paused = true;
  } 
    else {
    	timer = setInterval(change, 3000); 
    	paused = false;
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GreatRash, 2015-10-27
@qo_0p

No need to call clearInterval , just return from change if paused === true .

K
Konstantin Gromov, 2015-10-27
@Pathgk

var pauseButton = document.querySelector(".pause-button"),
    start = Date.now(),
    duration = 3000,
    timePassed,
    paused;



var timer = setInterval(change, duration);

pauseButton.addEventListener("click", function() {
  if (!paused) {
    clearInterval(timer);
    timePassed = Date.now() - start;
    paused = true;
  } else {
    setTimeout(function() {
      timer = setInterval(change, duration);
    }, duration - timePassed);

    paused = false;
  }
}, false);



function change() {
  // ...
}

upd: The original version was somewhat incorrect - corrected.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question