Solved

timeout function with a countdown timer

Posted on 2008-10-20
16
586 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
 
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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…

706 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