id = setInterval () сначала не определено, чем 3 (использует Jquery) - PullRequest
0 голосов
/ 16 мая 2011

Я хотел бы иметь счетчик, который считает в обратном направлении и останавливается, если пользователь заполнил поле ввода.

К сожалению, счетчик не останавливается - я пытался прочитать идентификатор счетчика во многих местахкода и не может видеть логику, в которой это меняет значение (возможно, я неправильно понимаю, как работают SetInterval () и clearInterval () ...

Соответствующая часть кода:

$(document).ready(function() {
    var counter=0;
    function hole_erste_Frage(aktuelle_div, nr){
     $.ajax({
        url: 'gnkid.php',
        data: 'sectionid='+sectionid+'&nr='+nr,
        success: function(data)          
        {
          if ($('.dbantwort').eq(aktuelle_div).val().length>0) {
            console.log(counter); // "0"
            counter = start_counter($('.dbantwort').eq(aktuelle_div).val().length*2+5);
            console.log(counter); // "undefined" - WHY????
          }
        }
     });
    }
    hole_erste_Frage(aktuelle_div,aktuelle_div);
    function start_counter(count) {
        console.log(counter); // 1. call: "undefined" - 2. call: "3" !!! - Why 3??
        if (count<3) {count=3};
        var cnt=count*10;
        counter = setInterval(function() {
          console.log(counter); // still "undefined" than "3"
          if (cnt >= 0) {
                var sek=Math.floor(cnt/10);
                var zsek=cnt/10;
                if (sek<5){
                    $('#displayCounter').html(zsek);
                } else {
                    $('#displayCounter').html(sek);
                }
                cnt--;
                return_prevent--;
                question_time=question_time+100;
            }
            else {
                console.log(counter); // "undefined" - "3"            
                stop_counter(counter,'Timeout!!');                
            }
        }, 100);
        console.log(counter); // and still "undefined" - I don't understand!
     }
function stop_counter(cter,bool){
    clearInterval(counter);  // I think here is the problem, because when it is called the first time the variable "counter" seems to be "undefined"
    if (bool!='') {$('#displayCounter').html(bool);}
}
function press_send(){ // This one is called after the user pressed "return"
    stop_counter(counter); // Here is the problem - it does not stop "undefined" - and "3"
    if (check_answer()) {
        $('.Abfrage-Box').eq(aktuelle_div).toggle();
        check_answer_sql($('.antwort').eq(aktuelle_div).val(),$('.kid').eq(aktuelle_div).val(),aktuelle_div, question_time, true);
        aktuelle_div = (aktuelle_div>=anzahl_abfrageboxen-1) ? 0 : aktuelle_div+1;
        $('.Abfrage-Box').eq(aktuelle_div).toggle();
        $('.antwort').eq(aktuelle_div).focus();
        if ($('.dbantwort').eq(aktuelle_div).val().length>0) {
            console.log(counter);
            start_counter($('.dbantwort').eq(aktuelle_div).val().length*2+5);
            console.log(counter);
        }

    } else {
        check_answer_sql($('.antwort').eq(aktuelle_div).val(),$('.kid').eq(aktuelle_div).val(),aktuelle_div, question_time, false);
        $('.antwort').eq(aktuelle_div).css('backgroundColor','red');
        $('.richtige_antwort').eq(aktuelle_div).toggle();
    }

}

1 Ответ

0 голосов
/ 16 мая 2011

Похоже, вы присваиваете различные значения счетчику ...

Я бы предложил добавить новую переменную вне функций, скажем, gCounterTimer.Всякий раз, когда вы вызываете setInterval(...), присваиваете эту новую переменную, то есть:

gCounterInterval = setInterval(...)

А затем, когда вам нужно очистить ее, используйте:

clearInterval(gCounterInterval)

Так ваш код будет выглядеть так:

var gCounterInterval;

$(document).ready(function() {
    var counter=0;
    function hole_erste_Frage(aktuelle_div, nr){
     $.ajax({
        url: 'gnkid.php',
        data: 'sectionid='+sectionid+'&nr='+nr,
        success: function(data)          
        {
          if ($('.dbantwort').eq(aktuelle_div).val().length>0) {
            console.log(counter); // "0"
            counter = start_counter($('.dbantwort').eq(aktuelle_div).val().length*2+5);
            console.log(counter); // "undefined" - WHY????
          }
        }
     });
    }
    hole_erste_Frage(aktuelle_div,aktuelle_div);
    function start_counter(count) {
        console.log(counter); // 1. call: "undefined" - 2. call: "3" !!! - Why 3??
        if (count<3) {count=3};
        var cnt=count*10;
        gCounterInterval = setInterval(function() {
          console.log(counter); // still "undefined" than "3"
          if (cnt >= 0) {
                var sek=Math.floor(cnt/10);
                var zsek=cnt/10;
                if (sek<5){
                    $('#displayCounter').html(zsek);
                } else {
                    $('#displayCounter').html(sek);
                }
                cnt--;
                return_prevent--;
                question_time=question_time+100;
            }
            else {
                console.log(counter); // "undefined" - "3"            
                stop_counter(counter,'Timeout!!');                
            }
        }, 100);
        console.log(counter); // and still "undefined" - I don't understand!
     }
function stop_counter(cter,bool){
    clearInterval(gCounterInterval);  // I think here is the problem, because when it is called the first time the variable "counter" seems to be "undefined"
    if (bool!='') {$('#displayCounter').html(bool);}
}
function press_send(){ // This one is called after the user pressed "return"
    stop_counter(counter); // Here is the problem - it does not stop "undefined" - and "3"
    if (check_answer()) {
        $('.Abfrage-Box').eq(aktuelle_div).toggle();
        check_answer_sql($('.antwort').eq(aktuelle_div).val(),$('.kid').eq(aktuelle_div).val(),aktuelle_div, question_time, true);
        aktuelle_div = (aktuelle_div>=anzahl_abfrageboxen-1) ? 0 : aktuelle_div+1;
        $('.Abfrage-Box').eq(aktuelle_div).toggle();
        $('.antwort').eq(aktuelle_div).focus();
        if ($('.dbantwort').eq(aktuelle_div).val().length>0) {
            console.log(counter);
            start_counter($('.dbantwort').eq(aktuelle_div).val().length*2+5);
            console.log(counter);
        }

    } else {
        check_answer_sql($('.antwort').eq(aktuelle_div).val(),$('.kid').eq(aktuelle_div).val(),aktuelle_div, question_time, false);
        $('.antwort').eq(aktuelle_div).css('backgroundColor','red');
        $('.richtige_antwort').eq(aktuelle_div).toggle();
    }

}
...