1

I am stuck into something which I can't seem to figure out. I am trying to pause and resume an animation using multiple setTimeout as it's clear from the code but it doesn't work for me.I took the code from: javascript: pause setTimeout(); I edited the code according to my program but it doesn't seem to work.It just starts the animation from the very first state for e.g I paused at var gT=setTimeout but it starts from var yT=setTimeout My code looks like this:

var start, remaining;

    
    function pause() {
        window.clearTimeout(yT);
        window.clearTimeout(gT);
        remaining -= Date.now() - start;
    };

    function resume() {
        start = Date.now();
        window.clearTimeout(yT);
        window.clearTimeout(gT);
        yT = window.setTimeout(function(){
            all();
            loop();
        }, remaining);
        gT = window.setTimeout(function(){
            all();
            loop();
        }, remaining);


    };

pause();
resume();
isaeed
  • 15
  • 4

1 Answers1

0

You need to declare and set remaining and start separately.

var start_yT,start_gT, remaining_yT, remaining_gT;

    
    function pause() {
        window.clearTimeout(yT);
        window.clearTimeout(gT);
        remaining_yT -= Date.now() - start_yT;
        remaining_gT -= Date.now() - start_gT;
    };

    function resume() {
        start = Date.now();
        window.clearTimeout(yT);
        window.clearTimeout(gT);
        yT = window.setTimeout(function(){
            all();
            loop();
        }, remaining_yT);
        gT = window.setTimeout(function(){
            all();
            loop();
        }, remaining_gT);


    };

pause();
resume();

And if you need to do with more advance version of pause/resume, this is the link . This create each timer separately runtime as we did manually.

Krishan Kumar
  • 394
  • 4
  • 13
  • I just have a question. Where does the start_yT/start_gT takes the value from? Should it be the variable for setTimeout? – isaeed Jul 04 '20 at 18:51
  • Hello, so I tried what you suggested but still the problem is the same like I mentioned in the description. The problem is animation starts from the very first state when I resume it. – isaeed Jul 04 '20 at 19:12
  • also you may try with removing start from this "remaining -= Date.now() - start;" => "remaining -= Date.now()" – Krishan Kumar Jul 04 '20 at 19:18
  • Thank you very much for your help but I am not allowed to share the code online. – isaeed Jul 04 '20 at 19:27
  • 1
    The link that you suggested finally worked out for me. Thank you so much. – isaeed Jul 04 '20 at 23:26