2017-09-23 17 views
1

我工作的一個純JavaScript遊戲我有射擊導彈這樣的想法是,當我點擊它拍攝導彈,幾秒鐘後,導彈是回到它的位置的平面並再次顯示其工作正常,但是當我點擊多次被堆疊,從而發生了什麼事是有很多點擊其中導彈是不是回到它的位置,我怎麼能解決這個時間?我如何只允許一次點擊,例如在3秒的時間內?或只有在導彈準備就緒時才允許點擊! 這是我的代碼!的JavaScript只允許點擊時的元件示

window.onclick = function() 
{ 

    var $ball1 = document.getElementById("ball1"); 

    // shooting the missile using css transition to get some delay 
    $ball1.style.top = "-12000px"; 

    // hide missile and get it back to it's position 
    setTimeout(function(){ 
     $ball1.style = "display:none; top:71px"; 
    }, 500); 

    // show missile again on plane 
    setTimeout(function(){ 
     $ball1.style = "display:block;"; 
    }, 1000);  

} 

回答

1

一個簡單的方法是使用一個變量來存儲處理點擊的最後時間,然後檢查已經過去的時間。在我的例子中,我使用lastTime來存儲的時間和我實施3000ms(3秒)的點擊之間的間隙。這個例子的輸出是簡單的記錄到控制檯,但是你可以把它改成任何你想要的。

var lastTime = -1; 
 
window.onclick = function() { 
 
    if (lastTime < 0 || (new Date().getTime() - lastTime >= 3000)) { 
 
    lastTime = new Date().getTime(); 
 
    console.log("firing missile"); 
 
    } else { 
 
    console.log("too soon"); 
 
    } 
 

 
}

+0

太感謝你了,這正是我期待:) –

1

爲了解決你面對你需要存儲的狀態allowNextClick,在此基礎上,你會決定是否執行進一步的代碼或不是問題。

var allowNextClick = true; 

window.onclick = function() 
{ 

    if(!allowNextClick) { 
     return; 
    } 
    allowNextClick = false; 

    // allow every 3 seconds 
    setTimeout(function() { 
     allowNextClick = true; 
    }, 3000); 

    var $ball1 = document.getElementById("ball1"); 

    // shooting the missile using css transition to get some delay 
    $ball1.style.top = "-12000px"; 

    // hide missile and get it back to it's position 
    setTimeout(function(){ 
     $ball1.style = "display:none; top:71px"; 
    }, 500); 

    // show missile again on plane 
    setTimeout(function(){ 
     $ball1.style = "display:block;"; 

     // allow next click after missile is back 
     allowNextClick = true; 
    }, 1000);  

} 
+0

得到同樣的結果:「( –

0
// define a Boolean to check if ball is just shoot 
var canShot = true; 

window.onclick = function() { 

    if (canShoot) { 
     var $ball1 = document.getElementById("ball1"); 

     // shooting the missile using css transition to get some delay 
     $ball1.style.top = "-12000px"; 

     // turn the Boolean canShot to false to prevent multiple trigger 
     canShot = false; 

     // hide missile and get it back to it's position 
     setTimeout(function(){ 

      $ball1.style = "display:none; top:71px"; 
     }, 500); 

     // show missile again on plane 
     setTimeout(function(){ 

      $ball1.style = "display:block;"; 
      // turn the Boolean canShot to true to make the ball can be shoot 
      canShot = true; 
     }, 1000); 
    } 
} 
+0

你或許應該在最後'setTimeout'設置'canShot'到TRUE; –

+0

@AlexandrFedotov感謝 –

相關問題