Solved

timeout function with a countdown timer

Posted on 2008-10-20
16
589 Views
Last Modified: 2012-05-05
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>
0
Comment
Question by:Erikal
  • 8
  • 8
16 Comments
 
LVL 36

Expert Comment

by:Zyloch
ID: 22761316
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
 
LVL 36

Expert Comment

by:Zyloch
ID: 22761322
Oh, I am sorry. I forgot to call the updateTimer() function in countdown(). Your countdown() function should be

function countdown() {
    timeLeft -= 1000;
    updateTimer();
}
0
 

Author Comment

by:Erikal
ID: 22761753
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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 36

Expert Comment

by:Zyloch
ID: 22761820
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
 

Author Comment

by:Erikal
ID: 22762120
Thank you.
It works fine.
How can I stop the timer when it reaches timeout.
Currently it continues counting  into negative numbers.
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 22762136
You should be able to just clear your interval:

   clearInterval(tId);
0
 

Author Comment

by:Erikal
ID: 22762164
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
 
LVL 36

Expert Comment

by:Zyloch
ID: 22762172
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
 

Author Comment

by:Erikal
ID: 22762333
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
 
LVL 36

Expert Comment

by:Zyloch
ID: 22762378
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
 

Author Comment

by:Erikal
ID: 22762381
Sorry I inserted in the for loop.
It is Ok now

Many thanks, that was really great help.

0
 

Author Comment

by:Erikal
ID: 22762420
Just one final small thing.
The zero does not show fior small seconds.
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 22762445
Sorry, I don't know what I was thinking at the time.

     displaySeconds = " " + displaySeconds;

should be

     displaySeconds = "0" + displaySeconds;
0
 

Author Comment

by:Erikal
ID: 22762446
Sorry I am such a beginner at this.
How would i call nextPage() inside countdown() when timeLeft == 0
0
 
LVL 36

Accepted Solution

by:
Zyloch earned 500 total points
ID: 22762489
function countdown() {
    timeLeft -= 1000;

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

Author Closing Comment

by:Erikal
ID: 31507964
Thank you very much indeed.
Everthing seems to be working fine.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Google Maps API and PHP 25 49
Select case on click 3 19
Call a function within the ASP code 4 19
Visual Studio npm 1 11
Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

856 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