var timer;
function startTimer(secs, elem) {
var element = document.getElementById(elem);
var randomclick = Math.floor(Math.random() * 4 + 1);
if (secs > 9) {
element.innerHTML = "0:" + secs;
} else if (secs > -1) {
element.innerHTML = "0:0" + secs;
} else if (secs < -1) {
clearTimeout(timer);
``
alert(randomclick);
if (randomclick == 1) {
buttonAPress();
}
if (randomclick == 2) {
buttonBPress();
}
if (randomclick == 3) {
buttonCPress();
}
if (randomclick == 4) {
buttonDPress();
}
}
secs--;
timer = setTimeout('startTimer(' + secs + ',"' + elem + '")', 1000);
}
当我启动该功能时,除了我使用clearTimeout(计时器)之外该功能不断重复的事实外,一切似乎都很顺利;我做错了什么?
答案 0 :(得分:1)
试试这个,这里是JSFiddle
var timer;
function startTimer(secs, elem) {
var element = document.getElementById(elem);
var randomclick = Math.floor(Math.random() * 4 + 1);
if (secs > 9) {
element.innerHTML = "0:" + secs;
} else if (secs > -1) {
element.innerHTML = "0:0" + secs;
} else if (secs < -1) {
clearTimeout(timer);
alert(randomclick);
if (randomclick == 1) {
buttonAPress();
}
if (randomclick == 2) {
buttonBPress();
}
if (randomclick == 3) {
buttonCPress();
}
if (randomclick == 4) {
buttonDPress();
}
}
secs = secs - 1;
timer = setTimeout(function() {
startTimer(secs, elem)
}, 1000);
}
startTimer(10, 'myDiv');
&#13;
<div id='myDiv'></div>
&#13;
答案 1 :(得分:0)
var timer;
var el = document.getElementById('el');
function startTimer(secs,elem){
var element = document.getElementById(elem);
var randomclick = Math.floor(Math.random()*4+1);
if (secs > 9){
element.innerHTML = "0:" + secs;
}
else if (secs > -1){
element.innerHTML = "0:0" + secs;
}
else if(secs < -1){
clearTimeout (timer);// `` <============ typo ??
alert ('randomclick => ' + randomclick + ' \nit works');
if (randomclick == 1){buttonAPress();}
if (randomclick == 2){buttonBPress();}
if (randomclick == 3){buttonCPress();}
if (randomclick == 4){buttonDPress();}
}
secs--;
timer = setTimeout('startTimer('+secs+',"'+elem+'")',1000);
}
startTimer(12 , 'el')
<div id='el'>p</div>
也许是一个错字
看不到问题,一切运转良好!