Reputation: 37
i'm new to javascript, and i'm trying to build some kind of memory game. the game works fine until the user clicks too fast on the cards and more than 2 cards are "open". the function is activated by clicking. i tried to check if the function is already active by adding a global var, set it to 1 ( function busy) at entrance and set it back to 0 (free) at the end. it didn't work. any ideas how to solve it? code is:
var isProcessed =0;
function cardClicked(elCard){
//check to see if another click is being processed
if(isProcessed===1){
return;
}
//if function is not already active - set it to "active" and continue
isProcessed=1;
//doing all kind of stuff
//setting function to "free" again
isProcessed=0;
}
Upvotes: 0
Views: 1532
Reputation: 218
I believe the problem with your code is that when you call the function it both processes and frees the card currently being clicked which allows other cards to be clicked as well.
A simple way to fix it is: (I'm assuming after two cards are clicked it will "close" and others will be available)
var isProcessed =0;
var selectedPair=[];
function cardClicked(elCard){
//add to the amount of cards processed
isProcessed++;
//If there are two cards "processed" then:
if(isProcessed===2){
//reset the amount processed after two cards have been opened
isProcessed=0;
//"close" card functionality
//clear the array of selected cards;
selectedPair=[];
return;
}else{
//add card to the selectedPair array so we can keep track
//which two cards to "close" after it resets
selectedPair.push(elCard);
//do all kinds of stuff
}
}
Upvotes: 1
Reputation: 92440
Your plan should work. As @JustLearning mentioned in the comment, it might be better to to disable the button instead of using a flag variable. This will offer visual clues to the user that they can't click.
Having said that, the important thing is that resetting your flag, or enabling he button, has to happen after //doing all kind of stuff
is done.
Assuming that //doing all kind of stuff
is something slow and asynchronous this means resetting it in the callback or when a promise resolves.
Here's a quick example that asynchronously runs a count. During the count isProcessing
is set to true. In the callback function — not after it — it resets the flag.
function someSlowThing(cb){
let n = 30
let i = 0
let d = document.getElementById('count')
let itv = setInterval(() => {
if (i > n) {
clearInterval(itv);
i = 0
return cb()
}
d.innerHTML = i++
}, 50)
}
var isProcessing = false;
function process(e){
if(isProcessing) {
console.log("wait please")
return
}
isProcessing = true
someSlowThing(() => {
isProcessing = false // <-- important that the happens in the callback
console.log('done')
})
// don't try to set isProcessing here, it will happen too soon.
}
<div id = 'count'>0</div>
<button onclick='process()'>start</button>
Upvotes: 0