countdown starts to count up after zero

M

Michael

I have this script that works the way I want except for one thing... Once it
hits zero it starts to count up and looks like this:

-1:0-1:0-1:0-18 with the last number counting up.

Can anyone help me find a way to stop it at zero?

Thank you,

Mike


<SCRIPT>
<!--
var timeInMin = "1"; //The minutes the count down should run.

var theDay = new Date()
var countDown = theDay.getTime()+(1000*60*timeInMin);
var TimeTill //The string that is going to put all numbers together and make
sense.

function countdown()
{
var today = new Date() //Create an Date Object that contains today's date.
var second = Math.floor((countDown - today.getTime())/1000)
/*Use getTime() to get the milisecond (1/1000 of a second) from now to
theDay.
and devide it into 1000 to get the seconds from now to theDay.*/


var minute = Math.floor(second/60) //Devide "second" into 60 to get the
minute
var hour = Math.floor(minute/60) //Devide "minute" into 60 to get the hour
var day = Math.floor(hour/24) //Devide "hour" into 60 to get the day

CDay= day //Correct day
CHour= hour % 24 //Correct hour, after devide into 24, the remainder
deposits here.
CMinute= minute % 60 //Correct minute, after devide into 60, the remainder
deposits here.
CSecond= second % 60 //Correct second, after devide into 60, the remainder
deposits here.

var TimeTill = "";

if(CDay)
{
TimeTill += CDay + ":";
}
if(CHour || CDay)
{
if(CHour < 10)
{
TimeTill += "0";
}
TimeTill += CHour + ":";
}
if(CMinute < 10)
{
TimeTill += "0";
}
TimeTill += CMinute + ":";
if(CSecond < 10)
{
TimeTill += "0";
}
TimeTill += CSecond;

document.clock.countdown.value = TimeTill //Make the particular form chart
become "Daytill"
var counter = setTimeout("countdown()", 1000) //Create the timer "counter"
that will automatic restart function countdown() again every second.
}
//-->
</SCRIPT>
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Tue,
1 Feb 2005 21:00:32, seen in Michael
I have this script that works the way I want except for one thing... Once it
hits zero it starts to count up and looks like this:

-1:0-1:0-1:0-18 with the last number counting up.

Can anyone help me find a way to stop it at zero?

function countdown()
{
var today = new Date() //Create an Date Object that contains today's date.
var second = Math.floor((countDown - today.getTime())/1000)

if (second<0) return // might well do it

Code should be indented to show structure. Read the newsgroup FAQ.
var counter = setTimeout("countdown()", 1000) //Create the timer "counter"
that will automatic restart function countdown() again every second.

It will not, in at least some browsers; the delay has overheads. To get
the right overall delay always, and to display every second, you *must*
resynchronise.


Rather than going to all that trouble to generate the display, how about
determining the initial delay D in seconds,
X = new Date(0,0,1,0,0,D) ;
then, at each seconds tick X.setSeconds(X.getSeconds()-1) ;
and use s = String(X).replace(/.*(\d)[^0-9]*([0-9:]{8}).*/, "$1-$2")
to generate the output as 2-16:06:22 - it assumes the count is less
than 10 days, and needs more testing; it assumes the day is the first
digits field, and the time is non-FFF.
Perhaps too risky.

But even better, in the loop use :
d = String(new Date(0,0,20,0,0,D--))
d = d.replace(/.*(\d)[^0-9]*([0-9:]{8}).*/, "$1-$2")
will generate a string like 0-00:00:10 but one second less each time;
stop when D<0.
 
R

RobG

Dr John Stockton wrote:
[...]
It will not, in at least some browsers; the delay has overheads. To get
the right overall delay always, and to display every second, you *must*
resynchronise.

Or run the function with an interval of say 200 so
synchronization jumps are not noticeable.

The OP may be interested in the following counter that gives the
years, months, days, hours, minutes and seconds from now to a
chosen date. It doesn't allow for Dr. J's favoured leap
seconds, but anyone who notices shouldn't be using a JavaScript
function for their timer...

It runs in less than 1 ms on a (reasonably new) Wintel box, so
it may as well run the full function each time. It means
modifying the numbers in the form changes the countown without
re-clicking the button (more an artifact than a feature...)


<html><head><title>play</title>
<script type="text/javascript">

// Stop date/time must be after
// current date/time.
function dateDiff(){

// Gets a stop date/time from form 'f'
// Caution: zero validation on input
var f = document.forms['dateFields'];
var s = new Date(
f.Yr.value,
f.Mn.value - 1,
f.Dy.value,
f.Hr.value,
f.Min.value,
f.Sec.value
);

var ele = document.getElementById('result') ||
document.all('result');

var n = new Date();
if (s < n) {
ele.innerHTML = '<b>Bzzzzt!!!</b><br>'
+ 'Alarm is ringing...';
return false;
}

// Diff years
var dyr = s.getFullYear() - n.getFullYear();
s.setFullYear(s.getFullYear() - dyr);
if (s < n) dyr -= 1;

// Diff months
var dmn = (s.getMonth() - n.getMonth() + 12) % 12;
s.setMonth(n.getMonth());
if (s < n) {
s.setMonth(+s.getMonth() + 1);
dmn -=1;
if (dmn < 0) dmn -= -12;
}

var tsec = Math.floor((s.getTime() - n.getTime()) / 1000);
var dsec = Math.floor(tsec % 60);
var dmin = Math.floor(tsec/60 % 60);
var dhr = Math.floor(tsec/3600 % 24);
var ddy = Math.floor(tsec/86400);

ele.innerHTML = 'Time left:'
+ ' ' + dyr + ' year' + addS(dyr)
+ ', ' + dmn + ' month' + addS(dmn)
+ ', ' + ddy + ' day' + addS(ddy)
+ ', ' + dhr + ' hour' + addS(dhr)
+ ', ' + dmin + ' minute' + addS(dmin)
+ ', ' + dsec + ' second' + addS(dsec);

setTimeout("dateDiff()", 200);
}

function addS(x) {
return (x != 1)? 's':'';
}

</script>

</head><body>
<form action="" name="dateFields">
<input type="text" size="8" name="Yr" value="2006">Year<br>
<input type="text" size="8" name="Mn" value="02">Month<br>
<input type="text" size="8" name="Dy" value="05">Day<br>
<input type="text" size="8" name="Hr" value="12">Hour<br>
<input type="text" size="8" name="Min" value="00">Min<br>
<input type="text" size="8" name="Sec" value="00">Sec<br>
<input type="button" value="Calc"
onclick="dateDiff()">
<input type="reset">
</form>
<br>
<span id="result">result will appear here...</span>
</body></html>
 
R

RobG

RobG wrote:
[...]
var tsec = Math.floor((s.getTime() - n.getTime()) / 1000);
var dsec = Math.floor(tsec % 60);
var dmin = Math.floor(tsec/60 % 60);
var dhr = Math.floor(tsec/3600 % 24);
var ddy = Math.floor(tsec/86400);

Slight modification required here. Because milliseconds are
truncated, the counter is one second ahead of itself. Fix:

var tsec = Math.floor((s.getTime() - n.getTime()) / 1000) + 1;
var dsec = Math.floor(tsec % 60) ;
var dmin = Math.floor(tsec/60 % 60);
var dhr = Math.floor(tsec/3600 % 24);
var ddy = Math.floor(tsec/86400);
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Thu, 3
Feb 2005 01:11:41, seen in RobG
<[email protected]> posted :

I believe that your posting agent is acting injudiciously. It gives in
your header a line
X-Trace: news.optus.net.au 1107393101 203.15.126.10
(Thu, 03 Feb 2005 12:11:41 EST)
Now, although we know that EST is Eastern Standard Time as used in the
East, where the clocks are ahead of Greenwich, there's a chronologically
retarded and rather vociferous gang (some of them were led by the
esteemed Mr Giuliani) who believe that there is an East in the West, and
hence locally use a form of EST and will be loth to believe in any
other.

Dr John Stockton wrote:
[...]
It will not, in at least some browsers; the delay has overheads. To get
the right overall delay always, and to display every second, you *must*
resynchronise.

Or run the function with an interval of say 200 so
synchronization jumps are not noticeable.

Some people have no sense of rhythm !!
The OP may be interested in the following counter that gives the
years, months, days, hours, minutes and seconds from now to a
chosen date.

What happens if the start date is June 2005 and the finish is Xmas 2005
when your clock jumps an hour forwards in the middle of the countdown?
It doesn't allow for Dr. J's favoured leap
seconds, but anyone who notices shouldn't be using a JavaScript
function for their timer...

??? One cannot deal with leap seconds using standard javascript (or PC,
Windows, etc.) routines; though one should be aware of them.

var ele = document.getElementById('result') ||
document.all('result');

For a single use, that looks better than
if (document.all && !document.getElementById) { // e.g. IE4
document.getElementById = function(id) {
return document.all[id] } }

I suppose the latter is better if getElementById is wanted at many
times/places?



I'm revising js-date1.htm on difference in Y M D, and have reached

function DiffDateC(A1, A2) { var dm, dd
dm = (12*A1[0]+A1[1]) - (12*A2[0]+A2[1]) ; dd = A1[2] - A2[2]
if (dd<0) { dm-- ; dd += DaysInMonth(A1[0], A1[1]-1) } // **
return [(dm/12)|0, dm%12, dd] }

Parameters and return are [Y,M,D]; note the ease of dealing with year
borrows. Note the light use of Date Object; only if the month length is
needed, and discussions last year showed how brief explicit code can do
that faster. Any comment?

Note that the YMD from, say, 2005-04-04 to 2005-06-03 differs from that
for the reversed interval of 2005-06-03 to 2005-04-04.
 
M

Matthew Lock

I believe that your posting agent is acting injudiciously. It gives
in
your header a line
X-Trace: news.optus.net.au 1107393101 203.15.126.10
(Thu, 03 Feb 2005 12:11:41 EST)
Now, although we know that EST is Eastern Standard Time as used in the
East, where the clocks are ahead of Greenwich, there's a chronologically
retarded and rather vociferous gang (some of them were led by the
esteemed Mr Giuliani) who believe that there is an East in the West, and
hence locally use a form of EST and will be loth to believe in any
other.

The poster's EST probably refers to Eastern Summer Time (or is that
Eastern Standard Time?) in Australia.
 
R

RobG

Dr said:
JRS: In article <[email protected]>, dated Thu, 3
Feb 2005 01:11:41, seen in RobG
<[email protected]> posted :

I believe that your posting agent is acting injudiciously. It gives in
your header a line
X-Trace: news.optus.net.au 1107393101 203.15.126.10
(Thu, 03 Feb 2005 12:11:41 EST)
Now, although we know that EST is Eastern Standard Time as used in the
East, where the clocks are ahead of Greenwich, there's a chronologically
retarded and rather vociferous gang (some of them were led by the
esteemed Mr Giuliani) who believe that there is an East in the West, and
hence locally use a form of EST and will be loth to believe in any
other.

Gosh, there I was, trolling through some old posts when...

Sorry Dr. J, I missed this reply. Yes, the time zone should
more correctly be AEST, as in Australian Eastern Standard Time,
but Mac OS X does not give me the facility to change it via the
GUI.

eBay would have it that for a good portion of the year, I am in
AEDST, which everyone else I know of thinks is AEDT, but there
you go. If you can quote me a definitive reference for timezone
abbreviations I'd be very grateful.

No doubt I could poke around in the guts of the underlying
FreeBSD/Darwin core and get the timezone to report something
more appropriate, but despite thoroughly missing my distant UNIX
past, I'm not about to try it.

[...]
What happens if the start date is June 2005 and the finish is Xmas 2005
when your clock jumps an hour forwards in the middle of the countdown?

Ah, but you assume that I am somewhere that daylight saving will
affect my reference to UT - but you'd be wrong. :)

I get your point, for some folk, the clock will leap backward an
hour. I guess times should be reduced to UTC/GMT before doing
any calculation.

[...]
I'm revising js-date1.htm on difference in Y M D, and have reached

function DiffDateC(A1, A2) { var dm, dd
dm = (12*A1[0]+A1[1]) - (12*A2[0]+A2[1]) ; dd = A1[2] - A2[2]
if (dd<0) { dm-- ; dd += DaysInMonth(A1[0], A1[1]-1) } // **
return [(dm/12)|0, dm%12, dd] }

Parameters and return are [Y,M,D]; note the ease of dealing with year
borrows. Note the light use of Date Object; only if the month length is
needed, and discussions last year showed how brief explicit code can do
that faster. Any comment?

Very neat, but a similar algorithm is required to account for
hours, minutes & seconds.

function DiffTime(T1,T2) {
var dt = (T2[0]-T1[0]+24)*3.6e3+(T2[1]-T1[1])*60+(T2[2]-T1[2]);
return ([
(dt/8.64e4) | 0, // days
Math.floor(dt/3.6e3) % 24, // hours
Math.floor(dt/60) % 60, // mins
dt % 60 // secs
]);
}

Which expects time in as [h,m,s] and returns [d,h,m,s]. It
expects the finish time to be the day following the start time.

A start time of 23:00:00 and finish of 01:00:00 returns 0,2,0,0
The reverse returns 1,22,0,0.
The time difference should never exceed 2,0,0,0
(00:00:00 to 24:00:00)
 
D

Dr John Stockton

JRS: In article <42233282$0$4776$5a62ac22@per-qv1-newsreader-
01.iinet.net.au>, dated Tue, 1 Mar 2005 00:59:32, seen in
news:comp.lang.javascript said:
Gosh, there I was, trolling through some old posts when...

Sorry Dr. J, I missed this reply. Yes, the time zone should
more correctly be AEST, as in Australian Eastern Standard Time,
but Mac OS X does not give me the facility to change it via the
GUI.

eBay would have it that for a good portion of the year, I am in
AEDST, which everyone else I know of thinks is AEDT, but there
you go. If you can quote me a definitive reference for timezone
abbreviations I'd be very grateful.

I don't know of one; but since there are duplicates in the abbreviations
actually used world-wide, it would not be very useful. I have seen such
a list; but, being of NA origin, it included only NA zones.

The military system of single-letter suffixes is well-defined - which
makes one wonder how the US forces manage in Afghanistan, 4.5 hours from
GMT - that may use J. What I know is in <URL:http://www.merlyn.demon.co
..uk/misctime.htm#Zones>.

Preferred practice is to use only UTC/GMT triliterals, and otherwise to
give the offset numerically.



Very neat, but a similar algorithm is required to account for
hours, minutes & seconds.

That's of little interest, because it is so easy. Already on that page.

There is just the question, shared with Date, of whether one wants civil
or true difference - in the civil case, there are 24 hours in every day,
but one of them may be empty or occur twice.

For Date, present view is that the calculation should depend on whether
the wish is for days-since or for days-until; it affects which month
gets borrowed.
 

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

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top