473,466 Members | 1,377 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

countdown starts to count up after zero

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>
Jul 23 '05 #1
8 3729
Michael wrote:
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:

[...]

Have a poke around Dr. John's site here:

<URL:http://www.merlyn.demon.co.uk/js-dates.htm>

See if you can't remove 75% of your code.

--
Fred
Jul 23 '05 #2
JRS: In article <z9********************@comcast.com>, dated Tue,
1 Feb 2005 21:00:32, seen in news:comp.lang.javascript, Michael
<no**@none.com> posted :
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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of 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
Dr John Stockton wrote:
[...]
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.


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>

--
Rob
Jul 23 '05 #4
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);

--
Rob
Jul 23 '05 #5
JRS: In article <hT*****************@news.optus.net.au>, dated Thu, 3
Feb 2005 01:11:41, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.auau> 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:
[...]
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.


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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of 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 #6
> 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.

Jul 23 '05 #7
Dr John Stockton wrote:
JRS: In article <hT*****************@news.optus.net.au>, dated Thu, 3
Feb 2005 01:11:41, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.auau> 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)
--
Rob
Jul 23 '05 #8
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, RobG <rg***@iinet.net.auau> posted :
Dr John Stockton wrote:
JRS: In article <hT*****************@news.optus.net.au>, dated Thu, 3
Feb 2005 01:11:41, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.auau> 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.


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.

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

function DiffDateC(A1, A2) { var dm, dd


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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #9

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

Similar topics

4
by: Christine | last post by:
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...
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....
9
by: Terry E Dow | last post by:
Howdy, I am having trouble with the objectCategory=group member.Count attribute. I get one of three counts, a number between 1-999, no member (does not contain member property), or 0. Using...
3
by: JimJam | last post by:
Hello Peeps I have created a program in VB.NET 2003 that counts down from 7.5 hours to zero from 08:00. I have a button that starts a new countdown from 1 hour to zero whilst the first one is...
4
by: tranky | last post by:
Hi programmers, i'm italian, and i need your help. Is it possible? There's a way to create a countdown control in asp.net? The control must shows in a label the countdown text. At the end of the...
5
by: WorldIsEnding | last post by:
How could i use the Timer component to count down from a certain number that i specify thats been entered into a variable? For example; Lets say i want to book a table at my local Snooker Club....
9
by: Yet Another One | last post by:
Sorry if this has been answered before, but I simply cannot find the solution on my own. I am looking to do a countdown in my application. Basically, I need to count down from 5:59 (5 minutes,...
4
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
I've got a Background Worker Thread that can take a long time. I've got a Progress Bar that updates, but I'd also like to include something about the time remaining that I can place on the status...
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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
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: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
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.