0

I am having trouble breaking out of a recursive setTimeout() and I do not know what I am doing wrong.

timer.start = function() {
  //do something here
  recursive(); //call the recursive once to start it up
  function recursive() {
    setTimeout1 = setTimeout {
      function() {
        //do something
        recursive();//call recursive after a delay
      }, delay}
  }
}

How would I stop that once the "pause" button has been hit?

I have tried this:

clearTimeout(setTimeout1);
<br />
setTimeout1 = null;

This does not work all the time.

DR. Palson_PH.d
  • 301
  • 1
  • 3
  • 11
  • What is _recursiveLoop()_ ? – Frank Cadillac Jul 01 '17 at 20:00
  • with the example you've provided, it looks like you're attempting a repeating timeout... if that's the case, have you looked at setInterval? https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval – Reinsbrain Jul 01 '17 at 20:17
  • @FrankCadillac That was suppose to be recursive(); I changed the name of the function but forgot to change that. – DR. Palson_PH.d Jul 06 '17 at 17:09
  • @Reinsbrain I am using this in a timer where I also have to deal with latency, setInterval does not allow for the (setTimeout(function, delay); ) delay parameter to be changed, so that is why I am using a recursive setTimeout. – DR. Palson_PH.d Jul 06 '17 at 17:11

1 Answers1

2

How about maintaining a single array for all timeouts?

var setTimeouts = [];

timer.start = function() {
  recursive();
  function recursive() {
      setTimeouts.push( setTimeout ( function() { recursive(); }, 1000 ) );
  }
}

Call this function when you want to stop the timers.

function clearTimeouts() {
    for (var i = 0; i < setTimeouts.length; i++) {
        clearTimeout(setTimeouts[i]);
    }
}
Junaid
  • 1,270
  • 3
  • 14
  • 33
  • I am planning on using these timers for a countdown timer, so wouldn't having so many setTimeouts be ineffective? – DR. Palson_PH.d Jul 06 '17 at 17:13
  • Why not use `setInterval()`? Example: `setInterval(function(){ // this code will be run every second }, 1000);` – Junaid Jul 06 '17 at 17:51