概念是创建一个提升操作。单击1后,显示器应显示1,其他楼层也应显示类似的情况。我已经完成了代码。
如果我连续点击2、3、4,则2楼具有在setTimeOut中设置的10000ms的延迟,但是3&4正在立即执行。
这是我的JSFIDDLE。
有人能帮我在四层楼等间隔吗。
var liftArray = [];
var liftCurrentPosition = 1;
$(document).ready(function(){
$("#currentPosHTML").text(liftCurrentPosition);
});
$(".floorbuttons").click(function(){
$(this).attr("disabled", true);
var selectedfloor = parseInt($(this).text());
console.log(selectedfloor);
if(liftArray == 0 || selectedfloor!=liftArray[liftArray.length-1]){
liftArray.push(selectedfloor);
setInterval(function(){
movelift(liftArray[0]);
liftArray.splice(0,1);
},10000);
}
});
function movelift(value){
$("#currentPosHTML").text(value);
liftCurrentPosition = value;
$(".floorbuttons").each(function(){
if($(this).text() == liftCurrentPosition){
$(this).attr("disabled",false);
}
});
};
使用setInterval
是正确的,但您必须确保只有在电梯当前不工作时才启动它。如果它工作,它将每5秒触发一次,当它到达所有楼层时,需要取消间隔。
因此,将其添加为一个通用变量:
var refreshIntervalId;
将点击功能更改为:
$(".floorbuttons").click(function(){
$(this).attr("disabled", true);
var selectedfloor = parseInt($(this).text());
console.log(selectedfloor);
if (liftArray == 0) {
refreshIntervalId = setInterval(function () {
movelift();
}, 10000);
}
if(liftArray == 0 || selectedfloor!=liftArray[liftArray.length-1]){
liftArray.push(selectedfloor);
}
});
最后更改movelift
函数:
function movelift(){
var value = liftArray.shift();
if (!value) {
clearInterval(refreshIntervalId);
return;
}
$("#currentPosHTML").text(value);
liftCurrentPosition = value;
$(".floorbuttons").each(function(){
if($(this).text() == liftCurrentPosition){
$(this).attr("disabled",false);
}
});
};
Fiddle
在movelift
函数中使用setTimeout
方法。