开发者

setTimout not stopping

I'm building a quiz and user has 5 seconds to respond to the question 开发者_JAVA百科if he doesn't respond within the time the answer is 3(which is a code for no answer). Timer updates just fine until you answer a question from that point the timer runs out of control you see 5,3,4,0 and go to the next question with the answer 3 does anyone know how to kill the old timer?

  function tijd(aantalSec){
    document.getElementById("sec").innerHTML = aantalSec;

    if(aantalSec == 0){
        clearTimeout(tijd);
        antwoord(3);
    }else{
        aantalSec = aantalSec - 1;
        var tijd = setTimeout('tijd(' + aantalSec + ',0)',1000);
    }
    }


Its a scope issue. Take tijid as a global variable. Also rename your variable to another name because it is confusing with the name of the function.

var intrID;

function tijd(aantalSec)
{       
   document.getElementById("sec").innerHTML = aantalSec;

   if(aantalSec == 0)
   {
       clearTimeout(intrID);
       antwoord(3);
   }
   else
   {
       aantalSec = aantalSec - 1;
       intrID = setTimeout('tijd(' + aantalSec + ',0)',1000);
   }
}


You should try to declare var tijd outside function and change timerID to something else like rahul mentioned.


Declare tijd outside the function to make it global. Also, rename it, it's confusing to have the name of a variable to be the same as the name of a function.


It's a scope issue like rahul said, but a better solution would be to use a static variable. You can accomplish this easily in javascript because functions are objects. So:

function tijd(aantalSec){

    document.getElementById("sec").innerHTML = aantalSec;

    if(aantalSec == 0){
        clearTimeout(tijd.timer);
        antwoord(3);
    }else{
        aantalSec = aantalSec - 1;
        tijd.timer = setTimeout('tijd(' + aantalSec + ',0)',1000);
    }
    }

The important bits are I"ve changed your variable from var tijd to tijd.timer which becomes persistant between calls to the function.

Globals are evil.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜