好的,我有一个没有任何Id的按钮,但是当它被点击时,它会启动一个名为buttonClick的函数。这个功能基本上控制一个老虎机(戳机),它的图像,奖金等。注意,有些代码可能无法工作,但请忽略它并想象它正在工作。但是,如果用户在这个函数完成之前点击播放按钮,它不会做任何事情,但仍然会完成它已经在做的函数,我该怎么做呢?很抱歉,这里没有我的完整长度的代码,但它的一个样本。
function buttonClick(){
var pic = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg");
var ex1 = pic[Math.floor(Math.random()*pic.length];
var ex2 = pic[Math.floor(Math.random()*pic.length];
var ex3 = pic[Math.floor(Math.random()*pic.length];
var moveImg = new Array("1.gif","2.gif","3.gif");
var timer = new Array("1000","5000","500","2000");
var time = Math.floor(Math.random()*4);
if (document.getElementById('coins').value > 0){
document.getElementById('coins').value -= 1;
pic[0].src = moveImg[0];
pic[1].src = moveImg[1];
pic[2].src = moveImg[2];
setTimeout(function(){
pic[0].src = ex1;
pic[1].src = ex2;
pic[2].src = ex3;
},timer[time])
}
else{
alert('Error insufficient tokens');
}
}
var in_progress = false;
function buttonClick(){
if(!in_progress){
var pic = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg");
var ex1 = pic[Math.floor(Math.random()*pic.length];
var ex2 = pic[Math.floor(Math.random()*pic.length];
var ex3 = pic[Math.floor(Math.random()*pic.length];
var moveImg = new Array("1.gif","2.gif","3.gif");
var timer = new Array("1000","5000","500","2000");
var time = Math.floor(Math.random()*4);
if (document.getElementById('coins').value > 0){
in_progress = true;
document.getElementById('coins').value -= 1;
pic[0].src = moveImg[0];
pic[1].src = moveImg[1];
pic[2].src = moveImg[2];
setTimeout(function(){
in_progress = false;
pic[0].src = ex1;
pic[1].src = ex2;
pic[2].src = ex3;
},timer[time])
} else {
alert('Error insufficient tokens');
}
}
}
或者,您可以将函数包装在闭包中,使in_progress
成为私有变量。
var buttonClick = (function(){
var in_progress = false;
return function(){
if(!in_progress){
var pic = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg");
var ex1 = pic[Math.floor(Math.random()*pic.length];
var ex2 = pic[Math.floor(Math.random()*pic.length];
var ex3 = pic[Math.floor(Math.random()*pic.length];
var moveImg = new Array("1.gif","2.gif","3.gif");
var timer = new Array("1000","5000","500","2000");
var time = Math.floor(Math.random()*4);
if (document.getElementById('coins').value > 0){
in_progress = true;
document.getElementById('coins').value -= 1;
pic[0].src = moveImg[0];
pic[1].src = moveImg[1];
pic[2].src = moveImg[2];
setTimeout(function(){
in_progress = false;
pic[0].src = ex1;
pic[1].src = ex2;
pic[2].src = ex3;
},timer[time])
} else {
alert('Error insufficient tokens');
}
}
};
})();