简体   繁体   中英

JavaScript timer works only once + bootstrap 3 modals

everybody! I am a JavaScript novice.

I am making an online test, where questions are popping up several times during the test. Every question must have a timer. Unfortunately, my timer works only during the first question.

<button type="button" class="btn btn-default btn-lg" id="timer">10</button>

Here is my timer():

function timer(){
    var obj=document.getElementById('timer');
    obj.innerHTML--;

    if(obj.innerHTML<=3){
        $('#timer').removeClass("btn-default");
        $('#timer').addClass("btn-danger");
    }

    if(obj.innerHTML==0){
        $('#myModalTest').modal('hide');
        setTimeout(function(){},1000);
        play();
    }
    else{setTimeout(timer,1000);}
}

Here is how my questions pop up:

$("#start").click(function() {
    setTimeout(function() {
        pause();
        $('.test1').modal('show');
        setTimeout(timer,1000);
    }, 10000);      
});

$("#continue1").click(function() {
    setTimeout(function() {
        pause();
        $('.test2').modal('show');
        setTimeout(timer,1000);
    }, 10000);
});

On .test2 timer is always 10 and doesn't work.

Also I am wondering how to make next question pop up, if a user hadn't clicked anything and timer has come to 0, and a modal has hidden.

Thank you for your time and attention.

I have tried to reproduce your issue in this jsbin and I'm not sure if what I did was what you wanted. Try it and give me feedback.

I think that your issue was here:

function timer(){

    if(obj.innerHTML==0){
      ...
    }
    else{setTimeout(timer,1000);} // here 
}

if obj.innerHTML !== 0 is going to call timer each second, and this can be closing each pop up you open... but i'm not sure because I don't have all the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM