我对这里发生的事情感到困惑。测验第一次正常。然而,在第一场比赛之后,我遇到了各种各样的问题。我想单击相同的按钮“#start2”,开始并重新启动测验,即清除计时器,将所有变量恢复为0等,并显示第一个问题。就好像页面已被刷新一般。多次使用setInterval和clearInterval的问题
相反,我越来越快滴答作响,计时器正在增加正确的猜测等等。可怕。
我用modulo来衡量“#start2”div被点击的次数。在第一次点击时,启动计时器。第二次点击 - 我想重置计时器。第三次点击 - 启动计时器,等等。
任何帮助是大规模赞赏。
var n = 0;
var x = 0;
var p = 0;
var incTime;
function a(n) {
var x,y,z;
x = Math.floor((Math.random() * 3))
if(x == 0){y = 1; z = 2}else if(x == 1){y = 0; z = 2}else{y = 0; z = 1}
$("#question_holder2").text(questions[n].q);
$(".answer_holder2").eq(x).text(questions[n].a).data('answer', 'a');
$(".answer_holder2").eq(y).text(questions[n].b).data('answer', 'b');
$(".answer_holder2").eq(z).text(questions[n].c).data('answer', 'c');
}
$(document).ready(function() {
//timing element
function startTimer(x){
$("#start2").text(x);
}
$("#start2").click(function(){
var setTimer;
p++;
//if it's been clicked before
if(p%2 === 0){
clearInterval(setTimer);
$("#start2").text("Start");
n = 0;
x = 0;
a(n);
alert("okay");
}else if(p%2 !== 0){
//never been clicked before
a(n);
setTimer = setInterval(function(){startTimer(x=x+1)}, 1000);
$('.answer_holder2').click(function() {
//correct answer given
if ($(this).data('answer') === 'a') {
n++;
if (n < questions.length) {
a(n);
} else {
alert("End of quiz!");
clearInterval(setTimer);
$("#start2").text("You took " + x + " seconds, you answered " + n + " questions correctly, with - incorrect answers given.");
x = 0;
n = 0;
a(n);
}
}else{
//incorrect answer given
$(this).fadeTo(1000,0.4);
var timeString = $("#start2").text();
var incTime = (timeString * 1) + 5;
$("#start2").text(incTime);
startTimer(incTime);
x = incTime;
};
});
};
});
});
您应该在脚本顶部的变量中定义'setTimer'在全局范围内。 – 2013-02-08 14:39:33
@SeainMalkin其实你不应该在全局范围内定义**任何**。 – freakish 2013-02-08 14:48:26
@freakish这是真的,但由于他已经定义了一堆全局变量,缺乏对范围的一些理解,我决定保持简单。 – 2013-02-08 14:52:20