1

I want to use counter variable in javascript like static variable with timer. counter must decrease by 1 on every second. I m working on online exam. on answering a question new question comes on the same page. my problem starts when counter variable is initialized with new question(means new page). counter variable does not persists on new page...suggest any solution

<script language="JavaScript">

function ExamTimer() 
{   
if ( typeof ExamTimer.counter == 'undefined' )   
{   
ExamTimer.counter = 30000;  // 30 min
    }
else
{

 ExamTimer.counter = ExamTimer.counter-1;   
    if(ExamTimer.counter<=0)
    {
          alert("exam finish");
     }
setTimeout(ExamTimer, 1000);

  }
window.onload=ExamTimer;
</script>
Boaz
  • 19,892
  • 8
  • 62
  • 70
St.
  • 143
  • 1
  • 6
  • how do you load the new question? via page refresh or via ajax call? using ajax will minimize page reloads – Amitd Mar 17 '13 at 11:09
  • I have to ask - why are you storing the number of elapsed seconds rather than the start time? By storing the server start time your app would give more realistic results and not suffer from any distortion given interceding servers etc. – Paul Mar 17 '13 at 11:18

2 Answers2

3

Javascript variables are not meant to outlive the current page load. The browser's Javascript engine executes the code on every page load (though most browsers cache the complied code), so client-side variables are lost whenever the page reloads.

There are several common methods to pass values from one page to another:

  1. DOM storage
  2. Cookies
  3. Server-side variables via a GET or POST request

Whatever method you select, remember it needs to be adequately resilient to unwanted manipulation by the user.

Community
  • 1
  • 1
Boaz
  • 19,892
  • 8
  • 62
  • 70
2

Using ajax pass value from one to another page. use session to hold last remainTime thai is passed to next page

<script language="JavaScript">

 function ExamTimer() 
 {   
 if ( typeof ExamTimer.counter == 'undefined' )   
 {   
  ExamTimer.counter = <cfoutput>#session.RemainTime#</cfoutput>;
  }
  else
   {

 ExamTimer.counter = ExamTimer.counter-1; 
 $.get('linktosend.cfm',{counter:ExamTimer.counter},function(responseText)
    { 
// value of ExamTimer.counter send to linktosend.cfm and store in session.RemainTime           
 });  
 if(ExamTimer.counter<=0)
 {
       alert("exam finish");
 }
setTimeout(ExamTimer, 1000);

 }
 window.onload=ExamTimer;

 </script>