Pause and resume javascript code


I have a function that runs using setInterval and I want to pause/stop the execution and resume from where it stopped. However, when i use the clearInterval it stops the function and resets the timer.

 var interval;

      //tell sigma how to animate a node
      function autoDraw(seconds){

           //read the json file
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var myObj = JSON.parse(this.responseText);
                //console.log("Json parsed data is: " + JSON.stringify(myObj));

                //create a new sigma instance and load all nodes and edges into it
                var mySigma3 = new sigma({ 
                  graph: { "nodes":myObj.nodes,"edges":[]},//fills only with the nodes
                  container: 'graph-container',
                  settings: {
                      minEdgeSize: 1,
                      maxEdgeSize: 5,

                //animated edge drawing 
                 interval = setInterval(function() {
                        if (seconds < 0) clearInterval(interval); //break the interval
                          if(!mySigma3) { return; } //Don't do anything until the nodes have been set up.

                          var edgeinplace = mySigma3.graph.edges().length;
                          if(edgeinplace < myObj.edges.length) { //Prevent trying to push the button too many times.


                          // Refresh the renderers to make the changes effective:
                    }, 1);"GET", "data/arctic.json", true);

            function pause(){
            // Pausing (which is really stopping)



This looks more like the sigma object should be a Promise or event emitter, as it looks like you want setInterval() to mimic that behaviour.


Hi, I want to pause and play the animation that i created. Can I save the time the function was stopped and continue from it somehow?


Then you should create a component, that manages the animation for you.

The crucial part you need to figure out is how to store the state of your animation. And from the looks of it, setInterval() is the wrong tool to use. I guess an evented system should be used so you can send interrupts to it.


Okay, thanks! I will have a look.