0

Using Javascript/jQuery, how can I pause (or resume) the following loop when the "P" key is pressed?

(function() {
   var arr = [...],
       len = arr.length;


   (function doProcess(i) {
       if (i) {
            console.log(len - i);
           /* do something with arr[len - i] */
           setTimeout(function() { doProcess(--i); }, 20000);
       }
   })(len);    
})();
Community
  • 1
  • 1
Matt V.
  • 9,703
  • 10
  • 35
  • 56

2 Answers2

6

Pausing and resuming is fairly complex. What you really have to do is this:

  1. Start a process and store its timeout ID.
  2. Store the time when you ran that process.
  3. On keypress, clear the timeout using its timeout ID.
  4. Store the unfinished time in another variable.
  5. On next keypress, set the timeout using that unfinished time.
  6. Set the following timeouts to the original intended delay.

Here's a more generalized jsFiddle example I whipped up.

var counterOn = true;
var delay = 3000; 
var lastRun;
var tempDelay;
var intervalId;

function decrementCounter() {
  // do something
  lastRun = new Date();
  timeoutId = setTimeout(decrementCounter, delay);
}

function toggleCounter() {
  var curTime = new Date();
  counterOn = !counterOn;
  if (counterOn) {
    lastRun = curTime.valueOf() + tempDelay - delay;
    timeoutId = setTimeout(decrementCounter, tempDelay);
  } else {
    clearTimeout(timeoutId);
    tempDelay = delay - (curTime.valueOf() - lastRun);
  }
}

$(document).keydown(function(e) {
  if (e.which === 80) {
    toggleCounter();
  }
});

decrementCounter();
brymck
  • 7,555
  • 28
  • 31
0

You'll want to keep track of how much time has passed with your timer (see here: javascript: pause setTimeout();) and call clearTimeout on whatever event you want to stop, then call setTimeout again with your remaining time left once whatever event unpauses is fired again.

Community
  • 1
  • 1
kinakuta
  • 9,029
  • 1
  • 39
  • 48