开发者

Trying to create an infinite for loop that can stop using function doIt()

开发者 https://www.devze.com 2022-12-29 05:10 出处:网络
Hey guys, I\'m new to javascript and I\'m doing a project for my final in class. I need to make it so this game engine I manipulated causes the generation button to go for an infinite loop.

Hey guys, I'm new to javascript and I'm doing a project for my final in class. I need to make it so this game engine I manipulated causes the generation button to go for an infinite loop.

I also need to stop it using (Reset==1). Any help? Here's the code I have so far if that helps:

function generation()
{

 for(y2=0; y2<2500; y2++) 
 {
  tempmapactual[y2]=mapactual[y2];
 }

 for (g=0;g<2500;g++)
 {
  neighbours=0;
  for (h=0;h<8;h++)
  {
   if (g+coords[h]>0 && g+coords[h]<2499 && mapactual[g+coords[h]]=="white.gif") 
   {neighbours=neighbours+1;} 
  }
  if (neighbours>=4 || neighbours==1 || neighbours==0) 
   {tempmapactual[g]="black.gif";}

  if (neighbours==3) {tempmapactual[g]="white.gif";}
 }

 for(y3=0; y3<2500; ++y3) 
 {
  if (mapactual[y3]!=tempmapactual[y3])
  {
   mapactual[y3]=tempmapactual[y3];
   document.images[y3+offset].src=mapactual[y3];
  }
 }

} 




</script> 

<script>
function doIt()
{
   for (i=0; i<X; i++)
  {
    // This is where I have trouble. What part of generation() do I call?
  }

     if (Reset==1) break; // This will kill the loop instantly.
  }
}
</script>

<script>
window.onload(doIt($(X).value)));
</script>


<form> 
<input type="button" value="generate" onClick="generation();"> 
</form>

<form>
<input type="text">
</form>

<form>
<input type="button" value="Infinite Loop!" onclick="doIt(开发者_StackOverflow);"> 
</form>

<form>
<input type="button" value="Reset" onclick="doIt();">
</form>


JavaScript is not multithreaded and you cannot break out easily of an infinite loop. Most browsers/JavaScript will detect out of control spinning and kill execution.

If you are writing a game engine, a better use of your CPU cycles is to set a timer. That way you can stop the timer when it is no longer needed.


You can't break out of an already-running infinite loop from another function without threads; but you could take a slightly different approach: if your "infinite loop" happens by way of the function running one iteration and then using a setTimeout callback to call itself again after an interval, then it'll run 'continuously', while still being interruptable (by, say, setting some global flag variable in your doIt function, which generation can check when it's invoked, and exit if it's true.


I think you want to look at this article about timing delays. Whenever JavaScript is busy going calculates (including with generate()) it is unresponsive to button pushing and such. You want to limit how much that happens.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号