简体   繁体   中英

How to pause recursive JavaScript function? Function uses setInterval() to delay each iteration

        function live() { 

            middleMan = setInterval(processGeneration, speed);
            if (!dead) {
                window.clearInterval(middleMan);
                live();
            }
        }

This code is intended to run function processgeneration() every speed miliseconds, until dead is true. When the code is run, it returns

error: too much recursion

to the console. I have ignored this because the code still works as intended (apparently). Now I want to add a pause function, like this:

                if (!pause) {
                    live();
                    console.log(g); //for debugging
                }

but it does not react to the value of pause being changed (toggled by button click). neither is the value of g returned to the console. How do I resolve this isse?

Try this

  function live() { 
    if (dead) {
      clearInterval(middleMan);
      return;
    }
    // do something when alive
  } 
  var middleMan=setInterval(live,speed);

or

  function live() { 
    if (dead) {
      return;
    }
    // do something when alive
    setTimeout(live,speed);
  } 
  live();

You have called live() function recursively, which is not stoped ever, I think you want something like this, the processgeneration() is executing until dead is true.

var speed = 1000;
dead = false;

middleMan = setInterval(processGeneration, speed);
function live() { 
    if (dead) {
        alert('this will clear the set interval');
        window.clearInterval(middleMan);
    }
}

function processGeneration(){
    console.log("output ");
}

setTimeout(function(){
    dead = true; //put your condition here when your dead is true
    live();
}, 4000);

live();

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM