我有这个jquery代码来处理某些情况,如果用户单击向右或向左按钮但是当用户同时单击两个按钮时导航变得一团糟
$(document).ready(function(){
$(document).keydown(function(e){
if (e.keyCode == 37) {
setTimeout(LeftKeyPressed(),5000);
}
else if(e.keyCode == 39){
setTimeout(RightKeyPressed(),5000);
}
});
});
我想简单地阻止任何调用,直到第一个或第二个函数完全执行
答案 0 :(得分:0)
$(document).ready(function(){
var navt;
$(document).keydown(function(e){
if(navt != null) return;
if (e.keyCode == 37) {
navt = setTimeout(function(){ LeftKeyPressed(); navt = null; },5000);
}
else if(e.keyCode == 39){
navt = setTimeout(function(){ RightKeyPressed(); navt = null; },5000);
}
});
});
答案 1 :(得分:0)
使用flag
来阻止不必要的函数调用,
$(document).ready(function(){
var xKeyPressed = false;
$(document).keydown(function(e){
if (e.keyCode == 37 && !xKeyPressed) {
setTimeout(LeftKeyPressed(),5000);
}
else if(e.keyCode == 39 !xKeyPressed){
setTimeout(RightKeyPressed(),5000);
}
});
function LeftKeyPressed()
{
xKeyPressed = true;
//Your code
xKeyPressed = false;
}
function RightKeyPressed(){
xKeyPressed = true;
//Your code
xKeyPressed = false;
}
});
答案 2 :(得分:0)
如果您的代码正在运行LeftKeyPressed
或RightKeyPressed
,请设置一个简单的检查:
var inFunction = false;
$(document).ready(function(){
$(document).keydown(function(e){
if (e.keyCode == 37 && !inFunction) {
inFunction = true;
setTimeout(LeftKeyPressed(),5000);
}
else if(e.keyCode == 39 && !inFunction){
inFunction = true;
setTimeout(RightKeyPressed(),5000);
}
});
});
//Add this in your functions, both Left and Right variants,
function LeftKeyPressed(){
//Do your normal stuff here
inFunction = false;
}
还有其他方法可以做到这一点,但在我看来,这是一种清晰简洁的做法。您可以使用此方法获得race conditions。