1

I'm wondering if there was a way to "pause" a javascript setInterval command and then resume it a few seconds later, then go through the loop, pausing for a while, start looping again, pausing again etc.? In other words, when a logical condition is right, pause for a set amount of time before picking up again?

Using pseudo code, I was thinking something like:

setInterval(fn, 1000);

pausecondition = false;

fn()
{
  // do stuff, including pausecondition

  if (pausecondition == true)
  {
     // pause for two seconds
     // pausecondition = false
   }
}

What I'm trying for is a setInterval that works every 1000 milliseconds, then when the pause condition is true, the function pauses for two seconds and then setInterval resumes every 1000 milliseconds as before.

EventHorizon
  • 87
  • 1
  • 7

2 Answers2

0

How about using the setTimeout function like this?

var pausecondition = false;
var fn = function (){
  if (pausecondition) {
    setTimeout(function(){
      pausecondition = false;
      fn();
    }, 2000);
   } else {
     // no pause, run logic
   }
}

setInterval(fn, 1000);
Linus Oleander
  • 17,746
  • 15
  • 69
  • 102
  • Thanks Oleander. Could I ask a question please? I've checked some javascript sites and its says setTimeout can only be used once; is that the case here? The reason why I ask is I would like my code to run every 1000 ms, then after a while, pauses for 2000ms, then resumes every 1000 ms, and then pauses, and then picks up again etc. – EventHorizon Dec 03 '15 at 15:25
  • @EventHorizon In short; yes you can run multiply `setTimeout`. It looks like `setTimeout` is running in parallel from your perspective as javascript is using an event loop under the hood and not threads. But that's not something you have to take into consideration in the example above. – Linus Oleander Dec 03 '15 at 19:34
  • Thanks! It turned out that what I wanted to do threw up a whole raft of other problems so I simplified my approach (makes for more readable code too) – EventHorizon Dec 04 '15 at 02:03
  • @EventHorizon Awesome! Don't forget to accept the answer if you consider it correct – Linus Oleander Dec 04 '15 at 02:09
  • Cheers mate, no problem! – EventHorizon Dec 04 '15 at 02:22
0
var pauseCondition = {
    enabled: false,
    counter: 0,
    countTo: 2,
};

increment and check counter >= countTo

marsgpl
  • 552
  • 2
  • 12