这是我的代码,我试图得到它,所以当点击按钮时,你有可能砍伐树,当你不砍伐它使用计时器尝试做的树它再次(1秒后)。一旦树被砍掉,它就会设置一个5秒计时器,使其“无效”,直到计时器启动,然后它将再次“激活”。这需要您再次单击该按钮以开始循环。
var woodcuttingLevel = 0;
var count = 0;
var treeSpawn;
var reClick;
function cutTree(){
var randomEvent = Math.floor((Math.random()*7)+1);
document.getElementById("message").innerHTML = "chop " + count;
count += 1;
switch(randomEvent){
case 1:
//add a log
document.getElementById("treeActive").innerHTML = "inActive1";
treeSpawn=setTimeout(function(){spawnTree()},5000);
break;
case 2:
//add a log if over level 5
if(woodcuttingLevel >= 5){
document.getElementById("treeActive").innerHTML = "inActive2";
treeSpawn=setTimeout(function(){spawnTree()},5000);
}
reClick=setTimeout(function(){reClick()},1000);
break;
case 3:
//add a log if over level 8
if(woodcuttingLevel >= 8){
document.getElementById("treeActive").innerHTML = "inActive3";
treeSpawn=setTimeout(function(){spawnTree()},5000);
}
reClick=setTimeout(function(){reClick()},1000);
break;
case 4:
//add a log if over level 13
if(woodcuttingLevel >= 13){
document.getElementById("treeActive").innerHTML = "inActive4";
treeSpawn=setTimeout(function(){spawnTree()},5000);
}
reClick=setTimeout(function(){reClick()},1000);
break;
case 5:
//add a log if over level 17
if(woodcuttingLevel >= 17){
document.getElementById("treeActive").innerHTML = "inActive5";
treeSpawn=setTimeout(function(){spawnTree()},5000);
}
reClick=setTimeout(function(){reClick()},1000);
break;
case 6:
//add a log if over level 22
if(woodcuttingLevel >= 22){
document.getElementById("treeActive").innerHTML = "inActive6";
treeSpawn=setTimeout(function(){spawnTree()},5000);
}
reClick=setTimeout(function(){reClick()},1000);
break;
case 7:
//add a log if over level 30
if(woodcuttingLevel >= 30){
document.getElementById("treeActive").innerHTML = "inActive7";
treeSpawn=setTimeout(function(){spawnTree()},5000);
}
reClick=setTimeout(function(){reClick()},1000);
break;
default:
//error
}
}
function spawnTree(){
document.getElementById("treeActive").innerHTML = "Active";
clearInterval(treeSpawn);
clearInterval(reClick);
}
function reClick(){
cutTree();
}
reClick()函数不起作用,我不确定为什么。任何人都可以引导我找到答案吗?谢谢你的时间!
答案 0 :(得分:2)
reClick
函数不起作用,因为当您尝试调用它时它不再存在。
对于包含超时标识符的变量,您使用了相同的名称,因此在启动超时时它将替换该函数。为变量使用不同的名称。变化:
var reClick;
为:
var reClickTimer;
以及所有:
reClick=setTimeout(function(){reClick()},1000);
为:
reClickTimer=setTimeout(function(){reClick()},1000);
和
clearInterval(reClick);
为:
clearInterval(reClickTimer);
附注:由于setTimeout
方法将回调函数作为第一个参数,因此您不需要调用函数的函数表达式,您可以使用函数引用本身:
reClickTimer=setTimeout(reClick,1000);
答案 1 :(得分:0)
问题是当你执行这项任务时
reClick=setTimeout(function(){reClick()},1000);
您实质上是删除reClick
函数定义并将其替换为setTimeout
的结果,该结果是标识正在运行的超时操作的“id”。
您需要使用var reClick
之类的var reClickTimeout
重命名您在reClickTimeout=setTimeout(function(){reClick()},1000);
之上定义的变量,您可以像这样使用
clearInterval(reClick); -> clearInterval(reClickTimeout);
您当然还需要替换所有其他错位的引用,例如
{{1}}