0

我重新創建了JavaScript中的生命遊戲。它有效,但在計算上無效。我有這個功能等待幾代人之間。提高遊戲生命娛樂的計算效率

var speed = 500; //milliseconds 

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

500毫秒沒有任何反應,然後是海嘯的計算任務。這給了死亡時間和滯後的諷刺組合。我怎樣才能使用500毫秒?

+0

使用'setTimeout'來調用'live()'並且不要在它的內部調用它! – undone

回答

0

您可以使用

function live() { 
    processGeneration(); 
    if (!dead) { 
     setTimeout(live, speed); 
    } 
} 
live(); 

function live() { 
    processGeneration(); 
    if (dead) { 
     clearInterval(timer); 
    } 
} 
var timer = setInterval(live, speed); 

function live() { 
    processGeneration(); 
    if (!dead) { 
     requestAnimationFrame(live); 
    } 
} 
requestAnimationFrame(live); 

但要注意,如果你使用setInterval,每次調用live必須比speed再少了。