timeout function with a countdown timer

I have a timeout function for an online test page that disables the test input when the allowed time expires (15 minutes), which is working OK.
I also want to dispaly a countdown clock (seconds and minutes only) to show how much time is left.
The timeout script is as follows: How can I incorporate a countdown into this script, which will show the seconds running down.

<script type="text/javascript">
var minutes = 15;
var timeLeft = minutes*60*1000;
var tId = "";
var leave = "";
function countdown() { timeLeft -= 1000; }
window.onload=function() {
  leave = setTimeout("nextPage()", timeLeft);
  tId = setInterval('countdown()',1000);
}

      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" )
                  f.elements[i].disabled=true;
            }
      }
       function activate(f){
      if (timeLeft > 60000 && 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 Verbal Reasoning 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)
            {
                  f.elements[i].disabled=false;
            }
      return true;
      }
</script>
ErikalAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ZylochCommented:
Here is a simple example. Because you call the function countdown() every second, it would make sense to update the display there. First, place a timer area in your HTML. For example:

<div id="timer"></div>

Then, you would have these two functions:

function countdown() {
    timeLeft -= 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 = " " + displaySeconds;
    }

    timerArea.innerHTML = displayMinutes + ":" + displaySeconds;
}

Then, to initialize the timer area, make sure to call updateTimer() in your window.onload.
0
ZylochCommented:
Oh, I am sorry. I forgot to call the updateTimer() function in countdown(). Your countdown() function should be

function countdown() {
    timeLeft -= 1000;
    updateTimer();
}
0
ErikalAuthor Commented:
Dear Zyloch,
Thank you very much for this.
Could you also let me know how I would call the updateTimer() in the windows.onload.
Do I just and another
windows.onload=updatTimer();
Also, can Iplace the timer area in a form?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

ZylochCommented:
Notice that you are already calling multiple functions on window.onload, via an anonymous function:

window.onload = function() {
    // Grouped code here
}

Therefore, your new window.onload need only look like this:

window.onload=function() {
  leave = setTimeout("nextPage()", timeLeft);
  tId = setInterval('countdown()',1000);
  updateTimer();
}

You can of course place the timer variable in a form. Do you mean form text field? If so, you would change .innerHTML to .value, and as long as the form field has the right ID (id="timer"), you will be fine.
0
ErikalAuthor Commented:
Thank you.
It works fine.
How can I stop the timer when it reaches timeout.
Currently it continues counting  into negative numbers.
0
ZylochCommented:
You should be able to just clear your interval:

   clearInterval(tId);
0
ErikalAuthor Commented:
I also need to put an aleret message when the counter reaches 0, 'saying the time is up'.
I think I should probably start a new question for that.
0
ZylochCommented:
You only need to put that in the nextPage() function. In fact, you would probably put the clearTimeout() code in the nextPage() function too.
0
ErikalAuthor Commented:
OKI put the akert and clearTimeout()
in the nexpage() as follows:

      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" )
                  f.elements[i].disabled=true;
            clearInterval(tId);

            alert('Time allowed for the English test has expired! Please press the Maths Test button to continue');
            }
      }

the alert displays at 3 seconds to timeout and keeps repeating itself.
In other words everytime I click the OK button it comes back.
0
ZylochCommented:
That is because you have put it in the for loop. It might also be the case that for some reason your setTimeout and your setInterval are not synchronized. Your best bet then would be to call nextPage() inside countdown() when timeLeft == 0
0
ErikalAuthor Commented:
Sorry I inserted in the for loop.
It is Ok now

Many thanks, that was really great help.

0
ErikalAuthor Commented:
Just one final small thing.
The zero does not show fior small seconds.
0
ZylochCommented:
Sorry, I don't know what I was thinking at the time.

     displaySeconds = " " + displaySeconds;

should be

     displaySeconds = "0" + displaySeconds;
0
ErikalAuthor Commented:
Sorry I am such a beginner at this.
How would i call nextPage() inside countdown() when timeLeft == 0
0
ZylochCommented:
function countdown() {
    timeLeft -= 1000;

   if (timeLeft <= 0) {
      nextPage();
    } else {
       updateTimer();
    }
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ErikalAuthor Commented:
Thank you very much indeed.
Everthing seems to be working fine.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.