0

I am currently working on an animation where I had to use setTimeout to animate it.

Here is my html for the button "pause" which changes to resume on click:

<button type="button" id="pause">Pause</button>

Here is my JavaScript code where I am pausing the animation using the clearTimeout and clearInterval function of js.

document.getElementById("pause".addEventListener("click",function(){
    toggleText();
  clearTimeout(yT);
  clearTimeout(gT);
  clearTimeout(yTt);
  clearTimeout(rsT);
  clearInterval(sI);

I want to resume the animation from that very point where it was paused. I tried some functions suggested in other posts from Mr.Tim in this community but nothing is working out for me so far.

Dai
  • 141,631
  • 28
  • 261
  • 374
isaeed
  • 15
  • 4
  • 1
    clearTimeout "cancels" the timeouts, it does not "pause" them. You will need to create them again, so you need to store somewhere the details about that. How were they created? – Pac0 Jul 04 '20 at 12:52
  • Does this answer your question? [javascript: pause setTimeout();](https://stackoverflow.com/questions/3969475/javascript-pause-settimeout) – Kiran Maniya Jul 04 '20 at 12:53
  • `I created it using the following function: var timeout= setTimeout(function(){ //do something ; }, 1000); ` – isaeed Jul 04 '20 at 12:55
  • @KiranManiya Yeah I have tried that aswell but it's not working out for me. – isaeed Jul 04 '20 at 12:56

1 Answers1

1

Kiran linked another question which is probably a good solution for you.

As mentioned, there's no built-in pauseTimeout function.

However, a simpler way would be to have an if statement within your setTimeout. Something like:

let timeoutPaused = false;

setTimeout(function(){
    if (!timeoutPaused) {
        doSomething();
    }
}, 1000)

function toggleTimeout() {
    timeoutPaused = !timeoutPaused;
}

Then you can just call toggleTimeout when you want to turn it off or on. Plus you don't even need that as a separate function really, I just put it like so for educational purposes.

Yakko Majuri
  • 448
  • 3
  • 13
  • Hello so I tried what you suggested, what happens now is whichever state I pause the timer, it restarts from the very first state and hence causes more delay. It doesn't really resumes the timer from the point where it was paused. – isaeed Jul 04 '20 at 13:43