Reputation: 1075
Okay, so I have a button without any Id but when it is clicked it starts a function called buttonClick. This function basically controls a slot machine(poke machine) it's images, winnings etc. Note, some code may not work but please disregard this and imagine it working. But how can I make it so that if the user clicks the play button before this function is finished it won't do anything but will still finish the function it's already doing? Sorry for the inconvenience of not having my full length code in here, but a sample of it.
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');
}
}
Upvotes: 0
Views: 105
Reputation: 3284
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');
}
}
}
alternatively you can wrap the function in a closure to make the in_progress
a private variable.
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');
}
}
};
})();
Upvotes: 2