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

x
?
Solved

timeout function with a countdown timer

Posted on 2008-10-20
16
Medium Priority
?
602 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
[X]
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
  • 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 2000 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: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
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…

664 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