Countdown timer inaccurate - losing time!?!

C

Christine

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;
}
 
L

Lasse Reichstein Nielsen

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
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Sun, 25 Jul 2004 05:56:04, seen in Christine
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
 
C

Christine

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 said:
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
 
L

Lasse Reichstein Nielsen

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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top