大家好,我是javascript的新手,我正在为我的期末考试做一个项目。我需要让它,这样我操纵的游戏引擎就会导致生成按钮无限循环。
我还需要使用(Reset==1)来停止它。有什么帮助吗?以下是我到目前为止的代码,如果有帮助的话:
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();">
</form>
<form>
<input type="button" value="Reset" onclick="doIt();">
</form>发布于 2010-05-07 07:57:15
JavaScript不是多线程的,你不能轻易地跳出无限循环。大多数浏览器/JavaScript都会检测到失控的旋转并终止执行。
如果你正在写一个游戏引擎,更好的利用你的CPU周期是设置一个计时器。这样,您可以在不再需要计时器时停止计时器。
发布于 2010-05-07 08:04:11
你不能从另一个没有线程的函数中中断已经在运行的无限循环;但是你可以采取一种稍微不同的方法:如果你的“无限循环”发生在函数运行一次迭代,然后使用setTimeout回调在一段时间后再次调用自己,那么它将“连续”运行,同时仍然是可中断的(例如,通过在doIt函数中设置一些全局标志变量,generation可以在调用时检查该变量,如果为真,则退出。
发布于 2010-05-07 08:04:07
我想你应该看看this article关于计时延迟的内容。每当JavaScript忙于计算(包括使用generate())时,它都不会响应按钮按下之类的操作。你想要限制这种情况的发生程度。
https://stackoverflow.com/questions/2785281
复制相似问题