我正在开发一款纯粹的JavaScript游戏我有一架射击导弹的飞机所以这个想法是当我点击它射击导弹时几秒钟后导弹回到它的位置并再次显示其工作正常但是当我多次点击它是堆栈所以发生的事情是有很多点击导弹没有回到它的位置我怎么能解决这个?如何在3秒钟内只允许一次点击?或仅在导弹准备就绪时允许点击! 这是我的代码!
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);
}
答案 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);
}
答案 1 :(得分: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");
}
}
&#13;
答案 2 :(得分: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);
}
}