2017-11-11 117 views
0

我正在做一個瀏覽器的遊戲,需要能夠無需重新加載頁面重新啓動,但我不希望因爲某些事情需要不同的使用Location.reload()(我不想比賽的狀態恢復到什麼是第一次加載頁面時)。所以,我想再次使用的setInterval當遊戲結束時(如果某些條件就像是一個按鍵真)再掀遊戲循環。使用的setInterval重新啓動瀏覽器遊戲

說我有一些功能稱爲主或init這我模塊的回報。假設main是這個模塊返回的唯一東西。

​​

repeatingFunc地方是行

loop = clearInterval(loop);

這實際上遊戲結束。此外,在repeatingFunc,還有如果爲true,將執行行

loop = setInterval(repeatingFunc, 100);

本次的setInterval的目的是開始再次的條件。我的方式是否設置不好?我真的不喜歡它是重複功能而不是重新啓動遊戲的主要功能。有什麼方法可以讓主要做這項工作?我對瀏覽器不太熟悉,以及如何正確使用多個setIntervals。如果您使用setInterval你僞造的瀏覽器繪製

var run = false; 

function loop(){ 
//whatever 
if(run) setTimeout(loop, 100); 
} 

function start(){ 
    if(run) return; 
    run = true; 
    loop(); 
} 

function stop(){ 
    run = false; 
} 

回答

1

您可以使用自重啓功能,等等。但是,如果你使用​​,當他與他以前做過抽獎,瀏覽器將調用。

// Get all requestAnimation from moost browsers 
 
var requestAnimation = window.requestAnimationFrame || 
 
    window.mozRequestAnimationFrame || 
 
    window.webkitRequestAnimationFrame || 
 
    window.msRequestAnimationFrame; 
 
window.requestAnimationFrame = requestAnimationFrame; 
 

 
// Get all cancelAnimationFrame from moost browsers 
 
var cancelAnimation = window.cancelAnimationFrame || 
 
    window.mozCancelAnimationFrame || 
 
    window.webkitCancelAnimationFrame || 
 
    window.msCancelAnimationFrame; 
 
window.cancelAnimationFrame = cancelAnimation; 
 

 
let run = false; 
 

 
function Update(time) { 
 
    console.log("run time: "+ time); 
 
    // If you do not use the boolean the requestAnimationFrame will be reactevate the animation frame. 
 
    if (run) 
 
     requestAnimationFrame(Update); 
 
} 
 

 
// Stops the requestAnimationFrame 
 
function Stop() { 
 
    cancelAnimationFrame(Update); 
 
    run = false; 
 
} 
 

 
// Starts the requestAnimationFrame 
 
function Start() { 
 
    run = true; 
 
    Update(0); 
 
}
<button type="button" onclick="Start();">Start!</button> 
 
<button type="button" onclick="Stop();">Stop!</button>

+0

你能解釋一下這是如何工作不同於我的例子嗎?如果我把你的循環功能爲主,不會我還需要從別的地方賽後在調用循環? – embracethefuture