Solved

JavaScript timer code question!  500 POINTS!!

Posted on 2004-10-21
291 Views
Last Modified: 2010-04-17
Hi,
I found the code below on the internet for a test timer.  I understand everything but the max time it allows is 60 minutes.  I have set it up so that after the first 60 minute session, another 60 minute session starts.  The code says that the max time is for 60 minutes.  I tried increasing the values so that the timer is for 120 minutes.  When I did that, the timer starts at 120 minutes and begins the countdown but then it starts jumping minutes sometimes by as much as 10 minutes.  Can someone please tell me how I can alter the code below so that the timer is for 120 minutes?

Thanks


function display(){
rtime=etime-ctime;
if (rtime>60)
m=parseInt(rtime/60);
else{
m=0;
}
s=parseInt(rtime-m*60);
if(s<10)
s="0"+s
window.status="Time Remaining (1st out of two 60 minute time period):  "+m+":"+s

window.setTimeout("checktime()",1000)
}


function display1(){
rtime=etime-ctime;
if (rtime>60)
m=parseInt(rtime/60);
else{
m=0;
}
s=parseInt(rtime-m*60);
if(s<10)
s="0"+s
window.status="Time Remaining (2nd out of two 60 minute time period):  "+m+":"+s

window.setTimeout("checktime1()",1000)
}




function settimes(){
alert("Test Format: 100 questions!  Timer can be seen at bottom-left of test page.")
alert("You have 2 hours time!  Timer will be split into two 60 minute sessions.")
alert("CLICK OK TO START TIMER!")

var time= new Date();
hours= time.getHours();
mins= time.getMinutes();
secs= time.getSeconds();
etime=hours*3600+mins*60+secs;
etime+=3600;  //You can change the value of 1200 according to how much time you wish to set the timer. Where 1200 is time in secs (1200 = 20 mins * 60 secs/min). Max time is 60 mins (3600secs)
checktime();
}

function checktime(){
var time= new Date();
hours= time.getHours();
mins= time.getMinutes();
secs= time.getSeconds();
ctime=hours*3600+mins*60+secs
if(ctime>=etime){
settimes1();
}
else
display();
}


function checktime1(){
var time= new Date();
hours= time.getHours();
mins= time.getMinutes();
secs= time.getSeconds();
ctime=hours*3600+mins*60+secs
if(ctime>=etime){
expired();
}
else
display1();
}



function settimes1(){
alert("You have 1 hour left!")

var time= new Date();
hours= time.getHours();
mins= time.getMinutes();
secs= time.getSeconds();
etime=hours*3600+mins*60+secs;
etime+=3600;  //You can change the value of 1200 according to how much time you wish to set the timer. Where 1200 is time in secs (1200 = 20 mins * 60 secs/min). Max time is 60 mins (3600secs)
checktime1();
}






function expired(){
alert("Time has expired!  Please click the Submit button now.  Delaying can void your test!");
//location.href="../main.html";  //Put here the next page
}



<BODY onLoad=settimes()....
0
Question by:NAPSR
    11 Comments
     
    LVL 1

    Expert Comment

    by:Perfunction
    Try setting up a variable that stores the timer length and replace every instance of 60 with that variable. Then, create another variable that stores the timer length seconds and replace every instance of 3600 with that variable.
    0
     

    Author Comment

    by:NAPSR
    Thanks for your input.

    I need the max time to be 120 minutes or 7200 secs.  Do I just replace th 3600 secs above with the variable that holds the 7200 secs?

    0
     

    Author Comment

    by:NAPSR
    Do I need to change anything in the display function?
    0
     
    LVL 1

    Expert Comment

    by:Perfunction
    Yeah, from the looks of things you need to replace all those hard-coded numbers with variables that can be used to control the timer. What I would do is setup on called timeMin and timeSec. Then you can set timeMin to 120 and set timeSec to timeMin * 60. I can't test the code here or I could help more
    0
     

    Author Comment

    by:NAPSR
    If its not too much trouble, can you copy and paste the code above with the suggested changes.  Thank you for your help.

    0
     
    LVL 1

    Expert Comment

    by:Perfunction
    if you post the entire page's code i can play with it over here
    0
     
    LVL 8

    Expert Comment

    by:sigmacon
    This code is unnecessarily complex. The following code achieves essentially the same without the hack of using the same functions twice. All you need to do is change the timeLimit to whatever you need. I did not add any of the display code to format hours and minutes. I can do it if you can't do it yourself. Put a call to the start() method in your body onload:

    var timeLimit = 7200;                  // time limit in seconds
    var intervalRef = null;            // reference to the interval id
    var startTime = null;

    function start() {
          alert('Click OK to start timer');
          startTime = new Date();
          intervalRef = setInterval('checkTimer()', 1000); // call every 1 second
    }

    function checkTimer() {
          var now = new Date();
          var timePast = now - startTime; // time past in milliseconds
          timePast = parseInt(timePast / 1000); // time past in seconds
          window.status = 'Time Remaining: ' + (timeLimit - timePast) + ' seconds';
          if (timePast >= timeLimit) {
                clearInterval(intervalRef);
                expire();
          }
    }

    function expire() {
          alert("Time has expired!  Please click the Submit button now.  Delaying can void your test!");
    }
    0
     

    Author Comment

    by:NAPSR
    Hi sigmacon,

    Thank you very much for your help.  I tried the display code but I can't seem to get it right completely.  Can you please help me with that?

    Thanks
    0
     
    LVL 8

    Accepted Solution

    by:
    var timeLimit = 7200;            // time limit in seconds
    var intervalRef = null;            // reference to the interval id
    var startTime = null;

    // add a leading 0 if necessary
    function leadZero(x) {
          return (x < 0 || x > 9 ? '': '0') + x;
    }

    // format a time given in seconds to hours:minutes:seconds
    function formatTime(aTime) {
          var hours = parseInt(aTime / 3600);
          var minutes = parseInt(aTime / 60) - hours * 60;
          var seconds = aTime - minutes * 60 - hours * 3600;
          return hours + ':' + leadZero(minutes) + ':' + leadZero(seconds);
    }

    function start() {
          alert('Click OK to start timer');
          startTime = new Date();
          intervalRef = setInterval('checkTimer()', 1000); // call every 1 second
    }

    function checkTimer() {
          var now = new Date();
          var timePast = now - startTime; // time past in milliseconds
          timePast = parseInt(timePast / 1000); // time past in seconds
          window.status = 'Time Remaining (hrs:min:sec): ' + formatTime(timeLimit - timePast);
          if (timePast >= timeLimit) {
                clearInterval(intervalRef);
                expire();
          }
    }

    function expire() {
          alert("Time has expired!  Please click the Submit button now.  Delaying can void your test!");
    }
    0
     
    LVL 8

    Expert Comment

    by:sigmacon
    NAPSR, how did this work out for you? Do you have any more questions?
    0
     

    Author Comment

    by:NAPSR
    Hi sigmacon,

    Sorry I have not written in a while.  I was out of town and just returned.

    The code is perfect!!  Thank you so much for helping me with it.  I have awarded you the points.  I will post any questions I might have about it here if needed.

    Thanks
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    Anonabox PRO Tor & VPN Router

    PRO is the most advanced way to fortify your privacy and online anonymity by layering the Tor network with VPN services. Use both together or separately, and without needing to download software onto your devices.

    Suggested Solutions

    Title # Comments Views Activity
    withoutString  challenge 40 98
    dog bark java program 15 55
    only14 challenge 19 50
    withoutTen challenge 14 50
    Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
    Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
    Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
    In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

    875 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now