Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


session elapsed time

Posted on 2008-10-24
Medium Priority
Last Modified: 2013-12-13
I have an online test with a set javascript time limit.
If the user submits the test they are not allowed back to the same page.
However, if the user leaves the page without submitting the test form, they can return anytime by loging in again.
What I need to do is to record the elapsed time at each session, so that I can restrict the total elapsed time for all sessions to a limit.
Say the user is allowed 1 hour for the test. In the first session they use up 20 minutes and in the next session 25 minutes. Finally they come back for the third time and when the remaining 15 minutes are up they are told the time is up.

Can someone please help me with the code on this.
So, can I for instance record the elapsed time to sql db and on the second session update the elapsed time by adding the elapsed time of the second session to the first one etc.

I am a beginner and your help with claer sample codes would be appreciated.
Question by:Erikal
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3

Expert Comment

ID: 22803907

I think when users take the test, you should store the start time in session. Then, when user leave the test (by clicking on "leave" link, for example), you can check current time to see how much time has passed. Then, you can add this time period to the total time your users had taken so far.
LVL 44

Expert Comment

ID: 22810161
no sessions will not work for this.  A session is open for as long as the user FIRST visits a page and makes some selection that the session records.  If he comes back later and does NOTHING at all, the session timer is still ticking.  He can come back 20 times in 20 hours, do absolutely nothing -- or do something -- and the session timer CONTINUES to tick regardless.  Sessions will not work for this ACTIVITY BASED timer.

You will have to use cookies, because only in that way can you record the ACTIONS or else INACTIONS of the user.  It is going to be tricky exactly how to do this, if you want a solution, suggest which actions will trigger a "continue" mode, and which actions will trigger a "terminate" mode.

Author Comment

ID: 22810996
Thank you scrathcyboy,
May be I can simplfy the problem.
If I set the initial number of minutes to 60 minutes (or 900,000 miliseconds) and record this in the db,   which is the time allowed for the test, and call it 'all_Time'. Then each time the student visits the page, I need to pass a variable (timeLeft) from the javascript to php and update the db with this.
In other words I do not need to deal with 'time()' in real terms, just the minutes and seconds remaining.
So, when the student comes back to the page next time, the updated minutes left in the db will become the new time limit.

Unfortunately, I am not quite sure how I should call these variables and how to pass them from javascript to php and back from php to javascript.

If I give you the script I am currently using, may be you can help me modify the script.
Here is the script for the whole time event of the test page: (I know I need to change
var timeLeft = minutes*60*1000;   to something like    var timeLeft = '<? echo $all_Time?>;':  to pass the sql var to javascript, but how and where in the script below do I pass the timeLeft to php so that the db can be updated.)

<script type="text/javascript">
var minutes = 2;
var timeLeft = minutes*60*1000;
var tId = "";
var leave = "";
function countdown() {
       timeLeft -= 1000;

      if (timeLeft<=0){
      } else {
window.onload=function() {
  //leave = setTimeout("nextPage()", timeLeft);
  tId = setInterval('countdown()',1000);

function updateTimer() {
   var timerArea = document.getElementById('timer');
   var numSeconds = timeLeft / 1000;
   var displaySeconds = numSeconds % 60;
   var displayMinutes = (numSeconds - displaySeconds) / 60;

   // format display a little more by putting a leading 0 for small seconds
   if (displaySeconds < 10) {
       displaySeconds = "0" + displaySeconds;

      timerArea.value = displayMinutes + ":" + displaySeconds;
      function nextPage(){
            //assuming you have <form id="English1"...>
            var f = document.getElementById("English1");
            for( var i=0; i < f.elements.length; ++i)
                    if( String(f.elements[i].type).toLowerCase() != "submit" )

            alert('Time allowed for the English test has expired! Please press the Maths Test button to continue');
       function activate(f){
  if (timeLeft > 100000 && confirm('Are you sure you want to leave the English test? You still have some time left to go back and check your answers. If you are sure you want to go on to the Maths Test, please click OK button. Otherwise, click Cancel button to return to the English test and use the remaining minutes to improve your English score.'))
return false;
            for( var i=0; i < f.elements.length; ++i)
      return true;
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

LVL 44

Accepted Solution

scrathcyboy earned 2000 total points
ID: 22816100
"Unfortunately, I am not quite sure how I should call these variables and how to pass them from javascript to php and back from php to javascript."

That's easy if you do it right.  You use a GLOBAL javascript variable, outside any function.  In the functions, you just USE the variable, not redeclare it, like this --


var timeleft = 6000;

your functions {

var getleft = timeleft;              // here you are not changing the global, just using it for a local var
 xxxxx                                          // cacluations
timeleft = getleft;            // after changing getleft time, you are now updating  the global

document.form1.time.value = timeleft;                  // put it into the input field before form submit

}   end your functions


FORM name="form1" method="GET" action="somefile.php">
<input type="hidden" name="time">

PHP ---

$timeleft = $ _GET["time"];

now it is in a php variable, manipulate it, and when you send back the response, put it back into the header --  HEAD -- <JAVASCRIPT>  var timeleft = <?php $timeleft ?>

Now it is written back to the head.  

Author Comment

ID: 22820128
I am working on this.
Just one question:
The whole javascript I copied above is also in the HEAD section. Should I put the 'var timeLeft = <?php $timeLeft ?>' in the same script block on top, just before 'var timeLeft = 6000;'

Would the two 'var timeLeft' declerations conflict?

Author Comment

ID: 22820257
another thing.
Can I actually put timeLeft in the db with the initial value of 6000 and update it with the new timeLeft value when the user leaves the page.
This way I would only have the 'var timeLeft = <?php $timeLeft ?>' in the javascript and can delete the 'var timeLeft = 6000;'

I need the timeLeft value updated in the db, so that everytimer the user leaves the page by refreshing or by navigating to another page, without actually using the 'submit' button of English1 form. When the user submits the English1 form the test is over and the timeLeft is no longer relevant.

Your suggestions are just what I am looking for, but how do I activate the sql update event when the user leaves the page without submitting the form.

I am sure this is quite simple, but I am such a beginner on this.
LVL 44

Expert Comment

ID: 22823911
"but how do I activate the sql update event when the user leaves the page without submitting the form."

You can't,  a server script will have to get the value at some point to save it.  The only other way is to use a cookie on the users system, and if the kids are smart enough, they can get around it.  The code I gave you basically saves the timeleft in a variable, and it will have to go to the server and be saved for the student, in a server cookie or session, and then passed back to the student when they sign on again.

None of this is simple programming, and if you don't know javascript, or ASP or PHP, and sessions and cookie management, I doubt you will be able to pull it off without a lot of reading and working with the code

Author Comment

ID: 22825931
Is there a way I can use an onUnload function to pass the timeLeft to server script.
I realy don't want to use cookies.

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

721 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