473,468 Members | 1,351 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Countdown timer inaccurate - losing time!?!

I've implemented a countdown timer for a tutorial web page that should
give the user 45 minutes to complete the test, only to find that the
timer is slowly 'losing' time. On average, it actually takes an extra
35 seconds, but has taken an extra 2.5 minutes in some cases. Any
ideas what might be the cause? And more importantly - the fix? Code
snippet below...

Thanks,
Christine

var gTimer=null;
var gTimerCount = 2700; //45 minutes

function CallTimer(num){ //this function is called when the page
is loaded
gTimerCount=num;
Timer();}

function Timer() {
window.status="";
gTimerCount--;
if (gTimerCount > 0)
{
if (gTimerCount == 300) TimeWarning();
window.status = "Time Remaining: " +
ConvertNum(gTimerCount) + " CT " + timeValue + " CTsecs " + ((hours *
3600)+(minutes * 60)+seconds);
gTimer=window.setTimeout("Timer()",1000);
}
else{
//OpenWin.close();
window.document.forms[0].submit.click();}
}

function ConvertNum(numsecs) { return (Math.floor(numsecs/60)) +
":" + AdjustNum(numsecs % 60); }

function AdjustNum(numsecs) {
if (numsecs < 10) return "0"+ numsecs;
else return numsecs;
}
Jul 23 '05 #1
4 4337
wi*********@yahoo.com (Christine) writes:
I've implemented a countdown timer for a tutorial web page that should
give the user 45 minutes to complete the test, only to find that the
timer is slowly 'losing' time. On average, it actually takes an extra
35 seconds, but has taken an extra 2.5 minutes in some cases. Any
ideas what might be the cause?


Each step in the countdown is triggered by (and triggers)
gTimer=window.setTimeout("Timer()",1000);
That is, when Timer is called, first it performs its own computations,
which takes some time, and then it schedules a new call one second
after that.

That means that the time between calls to Timer is not one second,
but one second + the time to execute the call to Timer().

You could probably get around that by using
setInterval(Timer, 1000)
However, on top of that, the timer might not be exact. It can only
perfectly match numbers that are a multiplum of the computer/OS's
internal timer frequency. If 1000 isn't that, it might round it
to 1024 or something. That is also a problem for long stretches
of short intervals.

My suggestion is to keep track of the time yourself:
---
function countdown(endAction, totalSecs, stepAction, stepFreq) {
var timeout = new Date();
timeout.setSeconds(timeout.getSeconds() + totalSecs);
function countdownStep() {
var now = new Date();
var timeLeft = timeout - now;
if (timeLeft <= 0) {
clearInterval(id);
endAction();
} else {
stepAction(timeLeft);
}
}
var id = setInterval(countdownStep, stepFreq);
}
---
Then you can call it as:
---
countdown(
function() {
document.forms[0].submit.click(); // if you didn't call the button
// submit, you could just do
// .forms[0].submit()
},
2700,
function (timeLeft) {
window.status = "time left: " + timeLeft + "ms"; // or whatever
},
500);
---
The first function is called when the countdown ends.
The second argument is the seconds before that happens.
The third argument is the function that is called for each "tick".
The fourth argument is the milliseconds between ticks.

This should not be off by more than the tick-size.

Good luck.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #2
JRS: In article <26*************************@posting.google.com> , dated
Sun, 25 Jul 2004 05:56:04, seen in news:comp.lang.javascript, Christine
<wi*********@yahoo.com> posted :
I've implemented a countdown timer for a tutorial web page that should
give the user 45 minutes to complete the test, only to find that the
timer is slowly 'losing' time. On average, it actually takes an extra
35 seconds, but has taken an extra 2.5 minutes in some cases. Any
ideas what might be the cause? And more importantly - the fix?


Had you read the FAQ, you should have been led to the answer.

An error of 2.5 in 45 is about 1 in 18. I imagine those are Win98-class
systems, where the clock runs at 18.2 Hz.

An error of 35 in 45*60 is about 1 in 80. I imagine those are WinNT-
class systems, where the clock runs at 100 Hz.
Note that, as well as the overheads in your program, the Timer must wait
till the next clock tick before it fires.

If you want something to happen once per computer second, you need a
lesser timeout, automatically compensating for delays - something like

setTimeout( S, 1010 - (new Date().getTime())%1000 )

That can possibly miss a tick if the computer is otherwise engaged for a
whole second; you might prefer to count in minutes.
If you want something to happen when the computer clock reaches a
certain time, you could loop waiting for that time. In order not to hog
the machine, you should use setTimeout to look only once per second,
checking new Date().getTime() against the proper value (for efficiency).
Those are conceptually different, and the difference can be significant
if clock-adjusting software is run (but, coded properly, the start and
finish of Summer Time will not cause error).
See below; js-date1.htm#TaI

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #3
Lasse,
Thanks - I tailored your suggestion and I've got it working now. I
appreciate the help.
Just one other question about the code you posted...
Why do you have to specify "function" in the function call below? Are
you defining a function and why don't they have names?
countdown(
function() {
document.forms[0].submit.click(); // if you didn't call the button
// submit, you could just do
// .forms[0].submit()
},
2700,
function (timeLeft) {
window.status = "time left: " + timeLeft + "ms"; // or whatever
},
500);

Lasse Reichstein Nielsen <lr*@hotpop.com> wrote in message news:<1x**********@hotpop.com>... wi*********@yahoo.com (Christine) writes:
I've implemented a countdown timer for a tutorial web page that should
give the user 45 minutes to complete the test, only to find that the
timer is slowly 'losing' time. On average, it actually takes an extra
35 seconds, but has taken an extra 2.5 minutes in some cases. Any
ideas what might be the cause?


Each step in the countdown is triggered by (and triggers)
gTimer=window.setTimeout("Timer()",1000);
That is, when Timer is called, first it performs its own computations,
which takes some time, and then it schedules a new call one second
after that.

That means that the time between calls to Timer is not one second,
but one second + the time to execute the call to Timer().

You could probably get around that by using
setInterval(Timer, 1000)
However, on top of that, the timer might not be exact. It can only
perfectly match numbers that are a multiplum of the computer/OS's
internal timer frequency. If 1000 isn't that, it might round it
to 1024 or something. That is also a problem for long stretches
of short intervals.

My suggestion is to keep track of the time yourself:
---
function countdown(endAction, totalSecs, stepAction, stepFreq) {
var timeout = new Date();
timeout.setSeconds(timeout.getSeconds() + totalSecs);
function countdownStep() {
var now = new Date();
var timeLeft = timeout - now;
if (timeLeft <= 0) {
clearInterval(id);
endAction();
} else {
stepAction(timeLeft);
}
}
var id = setInterval(countdownStep, stepFreq);
}
---
Then you can call it as:
---
countdown(
function() {
document.forms[0].submit.click(); // if you didn't call the button
// submit, you could just do
// .forms[0].submit()
},
2700,
function (timeLeft) {
window.status = "time left: " + timeLeft + "ms"; // or whatever
},
500);
---
The first function is called when the countdown ends.
The second argument is the seconds before that happens.
The third argument is the function that is called for each "tick".
The fourth argument is the milliseconds between ticks.

This should not be off by more than the tick-size.

Good luck.
/L

Jul 23 '05 #4
wi*********@yahoo.com (Christine) writes:
Just one other question about the code you posted...
Why do you have to specify "function" in the function call below? Are
you defining a function and why don't they have names?


I am defining a function, and it is a so-called anonymous function.
countdown(
I'm calling "countdown", and the first argument is:
function() {
document.forms[0].submit.click(); // if you didn't call the button
// submit, you could just do
// .forms[0].submit()
},


.... this function.
This is a function *expression* (as opposed to a function *declaration*).
It defines a function, but doesn't bind it to a name.

A function declaration is written in the same places as statements.
They both define the function and declare its name in the surrounding
scope. A function expression is written in the same places as
expressions. It only define the function, but doesn't declare a name.

Example:
---
function foo(f) {
f(function() { return 42;});
}
function bar(x) { return x + 37; }

alert(foo(bar));
---
In this example we have two function declarations, for the functions
"foo" and "bar". We use the value of "bar" as an argument to "foo".
Inside "foo", the variable "f" refers to the argument function (here
only "bar"). We call that with a third function, defined by a
function expression (the constant function that always returns 42).

Executing this will alert 79.

Good luck
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Bonnett | last post by:
I have been creating a generic countdown timer (source code below), counting the seconds, minutes, hours and days till an event, but I have having trouble with it finding out how many hours are...
1
by: Will | last post by:
I have form showing instructions and logging actions and I would like the form to show a count down timer for a certain period of time. E.g. 30 secs, going down to 0 and then displaying the action....
1
by: Dirk Hagemann | last post by:
Hi! I'd like to implement a countdown timer on a webite. It should show the months, days, hours, minutes and seconds until a given date and time. So far it's not really difficult, but this...
1
by: enggars | last post by:
Hello. Is there any way to create a countdown timer in ASP pages? I am working on some quiz project, and it needs time limitation. I tried to use the javascript as the time limitation. But the...
1
by: DennyLoi | last post by:
Hi everyone. I am trying to implement a countdown timer which is displayed on my page. The counter needs to countdown from 10 seconds to 0 upon the page loading up. I tried the following, but...
9
nomad
by: nomad | last post by:
Hello everyone again: Ok I figured out the quiz section and now I need to but a timer on the test. if anyone knows how to do a countdown timer that will only lasts for 30mins(or what ever time)...
9
by: MC | last post by:
I would like to display a timer in the corner of the page that shows the user how many minutes:seconds till the session times out. Are there any good examples out there? Google has again failed...
4
by: hanaa | last post by:
Hi I am making a test taker. I need to put up a countdown timer, and I haven't a clue how. Could someone please help me start. I google it and all I see is readymade scripts that can be downloaded....
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.