我是javascript的新手,我正在尝试构建某种记忆游戏。这个游戏运行良好,直到用户在卡片上点击过快,超过2张卡片被“打开”。点击即可激活该功能。我试图通过添加一个全局变量来检查函数是否已经激活,在入口处将其设置为1(函数繁忙),在结束时将其设置回0(空闲)。它没有起作用。有没有办法解决这个问题?代码为:
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;
}
发布于 2018-07-01 00:55:36
我认为您的代码的问题在于,当您调用该函数时,它既处理并释放当前正在单击的卡片,这也允许其他卡片被单击。
修复它的一个简单方法是:(我假设在点击两张卡片后,它将“关闭”,而其他卡片将可用)
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
}
}
发布于 2018-07-01 00:19:02
你的计划应该行得通。正如@JustLearning在评论中提到的,禁用按钮可能比使用标志变量更好。这将为用户提供他们无法单击的视觉线索。
话虽如此,重要的是重置你的标志,或启用按钮,必须在 //doing all kind of stuff完成后发生。
假设//doing all kind of stuff是缓慢和异步的,这意味着在回调中或在promise解析时重置它。
下面是一个异步运行计数的快速示例。在计数期间,isProcessing被设置为true。在回调函数中-而不是在它之后-它重置标志。
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>
https://stackoverflow.com/questions/51116424
复制相似问题