views:

45

answers:

4

Hi all,

I'm building a quiz and user has 5 seconds to respond to the qeustion if he doesn't resond within the time the answer is 3(wich is a code for no answer). Timer updates just fine until you answer a qeustion from that point the timer runs out of control you see 5,3,4,0 and go to the next qeustion 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);
    }
    }
+2  A: 

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);
   }
}
rahul
using a function property as a static variable eliminates the need for an ugly global. see my answer.
Stomped
Thank you very much it fixed the problem :-)
Ken
+1  A: 

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

S.Mark
+1  A: 

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.

zaf
+1  A: 

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.

Stomped