Solved

X Countdown Auto Restart

Posted on 2011-09-10
126
1,366 Views
Last Modified: 2012-05-12
Hello,

I want to set two variables in this JavaScript which are:

1. I want to set x to be the amount of time to countdown to, example 15 seconds

Once 15 seconds are reached I want to be able to put a message or a popup like how it is now, but the default message can be left empty and I’ll put something there myself later.

2. I want to set y to be the amount of time to restart the count, example 10 seconds

The current script counts down to midnight each day and restarts at midnight which is very good for certain circumstances but the revised scrip I need is one that counts down a certain amount of time and then stops while displaying nothing at all, then restarts again after a certain amount of time.

User mplungjan was the last person here to help me with this script when I changed it from a yearly countdown to a nightly midnight countdown and I must say he did a super job indeed.

Here is the code, please note I made two notes for you below in the code so you can see where the edits go:

<html>
<head>

<style style="text/css">

.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:yellow;
font: bold 18px MS Sans Serif;
padding: 3px;
}

.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}

</style>

<script type="text/javascript">

/***********************************************
* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this


var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


function formatresults(){
if (this.timesup==false){//if target date/time not yet met
var displaystring=arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until July 18, 2011 13:00:00"
}
else{ //else if target date/time met
var displaystring="Future date is here!"
}
return displaystring
}

function formatresults2(){
if (this.timesup==false){ //if target date/time not yet met
var displaystring="<span class='lcdstyle'>"+arguments[0]+" <sup>days</sup> "+arguments[1]+" <sup>hours</sup> "+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span> left until this Christmas"
}
else{ //else if target date/time met
var displaystring="" //Don't display any text
alert("Christmas is here!") //Instead, perform a custom alert
}
return displaystring
}

function formatresults3(){
  return (this.timesup)?"Midnight!":arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until midnight";
}

function formatresults4(){
if (this.timesup==false){ //if target date/time not yet met
var displaystring="<span class='lcdstyle'>"+arguments[0]+" <sup>days</sup> "+arguments[1]+" <sup>hours</sup> "+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span> left until midnight"
}
else{ //else if target date/time met
var displaystring="<span class='lcdstyle'>Midnight!</span>" //Display text
alert("Midnight!") //Custom alert
}
return displaystring
}

function formatresults5(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[0]+" <sup>day"   +(arguments[0]==1?"":"s")+"</sup> "+
    arguments[1]+" <sup>hour"  +(arguments[1]==1?"":"s")+"</sup> "+
    arguments[2]+" <sup>minute"+(arguments[2]==1?"":"s")+"</sup> "+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> left until midnight";
  // here the time is up:
  alert("Midnight"); // WILL however block the browser
  return "<span class='lcdstyle'>Midnight!</span>";
}

function formatresults6(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[1]+" <sup>hour"  +(arguments[1]==1?"":"s")+"</sup> "+
    arguments[2]+" <sup>minute"+(arguments[2]==1?"":"s")+"</sup> "+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> left until midnight";
  // here the time is up:
  alert("Midnight"); // WILL however block the browser
  return "<span class='lcdstyle'>Midnight!</span>";
}

// put new function here for the 15 second countdown with a 10 second auto restart, please keep code the same as function6 listed above as much as possible so changes are at a minimum 

</script>

</head>
<body>


<div id="countdowncontainer"></div>

<br>

<div id="countdowncontainer2"></div>

<br>

<div id="countdowncontainer3"></div>

<br>

<div id="countdowncontainer4"></div>

<br>

<div id="countdowncontainer5"></div>

<br>

<div id="countdowncontainer6"></div>

<br>

<div id="countdowncontainer7"></div>


<script type="text/javascript">

var futuredate=new cdtime("countdowncontainer", "July 18, 2011 13:00:00")
futuredate.displaycountdown("days", formatresults)


var currentyear=new Date().getFullYear()
//dynamically get this Christmas' year value. If Christmas already passed, then year=current year+1
var thischristmasyear=(new Date().getMonth()>=11 && new Date().getDate()>25)? currentyear+1 : currentyear
var christmas=new cdtime("countdowncontainer2", "December 25, "+thischristmasyear+" 0:0:00")
christmas.displaycountdown("days", formatresults2)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer3", midnightTonight.getTime())
futuredate.displaycountdown("days", formatresults3)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer4", midnightTonight.getTime())
futuredate.displaycountdown("days", formatresults4)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer5", midnightTonight.getTime())
futuredate.displaycountdown("days", formatresults5)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer6", midnightTonight.getTime())
futuredate.displaycountdown("hours", formatresults6)


<!-- Put new code here for div container 7 which I already made for you above, be sure I can edit x being the time to countdown and y being the time to restart the countdown as I like to change those two often -->

</script>

</body>
</html>

Open in new window


Please note, the new code should go in: <div id="countdowncontainer7"></div>

I left six other divs so you can see this code doing different things, as you can see it can do almost anything in regards to countdowns and countdown restarts.
0
Comment
Question by:Richard Morris
  • 63
  • 62
126 Comments
 

Author Comment

by:Richard Morris
ID: 36519454
Question:

Is there any way I can direct a specific issue directly to an expert?

If so I would like to direct this to: mplungjan

The reason I ask is I see nobody answered it and I already know he is good at working on these types of issues from past experience.
0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 36520857
do you mind if I can help?
Check this code
<html>
	<head>
		<style style="text/css">
			.lcdstyle
			{ /*Example CSS to create LCD countdown look*/
				background-color:black;
				color:yellow;
				font: bold 18px MS Sans Serif;
				padding: 3px;
			}
			.lcdstyle sup
			{ /*Example CSS to create LCD countdown look*/
				font-size: 80%
			}

		</style>

		<script type="text/javascript">
	/***********************************************
	* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
	* This notice MUST stay intact for legal use
	* Visit http://www.dynamicdrive.com/ for this script and 100s more.
	***********************************************/

			function cdtime(container, targetdate)
			{
				if (!document.getElementById || !document.getElementById(container)) return
				this.container=document.getElementById(container)
				this.currentTime=new Date()
				this.targetdate=new Date(targetdate)
				this.timesup=false
				this.updateTime()
			}

			cdtime.prototype.updateTime=function()
			{
				var thisobj=this
				this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
				setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
			}

			cdtime.prototype.displaycountdown=function(baseunit, functionref)
			{
				this.baseunit=baseunit
				this.formatresults=functionref
				this.showresults()
			}

			cdtime.prototype.showresults=function()
			{
				var thisobj=this
				var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
				if (timediff<0)
				{ //if time is up
					this.timesup=true
					this.container.innerHTML=this.formatresults()
					return
				}
				var oneMinute=60 //minute unit in seconds
				var oneHour=60*60 //hour unit in seconds
				var oneDay=60*60*24 //day unit in seconds
				var dayfield=Math.floor(timediff/oneDay)
				var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
				var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
				var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
				if (this.baseunit=="hours")
				{ //if base unit is hours, set "hourfield" to be topmost level
					hourfield=dayfield*24+hourfield
					dayfield="n/a"
				}
				else if (this.baseunit=="minutes")
				{ //if base unit is minutes, set "minutefield" to be topmost level
					minutefield=dayfield*24*60+hourfield*60+minutefield
					dayfield=hourfield="n/a"
				}
				else if (this.baseunit=="seconds")
				{ //if base unit is seconds, set "secondfield" to be topmost level
					var secondfield=timediff
					dayfield=hourfield=minutefield="n/a"
				}
				this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
				setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
			}

			function formatresults()
			{
				var displaystring = "";
				if (this.timesup==false)
				{//if target date/time not yet met
					displaystring = arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until July 18, 2011 13:00:00"
				}
				else
				{ //else if target date/time met
					displaystring = "Future date is here!"
				}
				return displaystring
			}

			function formatresults2()
			{
				if (this.timesup==false)
				{ //if target date/time not yet met
					var displaystring="<span class='lcdstyle'>"+arguments[0]+" <sup>days</sup> "+arguments[1]+" <sup>hours</sup> "+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span> left until this Christmas"
				}
				else
				{ //else if target date/time met
					var displaystring="" //Don't display any text
					alert("Christmas is here!") //Instead, perform a custom alert
				}
				return displaystring
			}

			function formatresults3()
			{
			  return (this.timesup)?"Midnight!":arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until midnight";
			}

			function formatresults4()
			{
				if (this.timesup==false)
				{ //if target date/time not yet met
					var displaystring="<span class='lcdstyle'>"+arguments[0]+" <sup>days</sup> "+arguments[1]+" <sup>hours</sup> "+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span> left until midnight"
				}
				else
				{ //else if target date/time met
					var displaystring="<span class='lcdstyle'>Midnight!</span>" //Display text
					alert("Midnight!") //Custom alert
				}
				return displaystring
			}

			function formatresults5()
			{
			  if (!this.timesup) return "<span class='lcdstyle'>"+
				arguments[0]+" <sup>day"   +(arguments[0]==1?"":"s")+"</sup> "+
				arguments[1]+" <sup>hour"  +(arguments[1]==1?"":"s")+"</sup> "+
				arguments[2]+" <sup>minute"+(arguments[2]==1?"":"s")+"</sup> "+
				arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> left until midnight";
			  // here the time is up:
			  alert("Midnight"); // WILL however block the browser
			  return "<span class='lcdstyle'>Midnight!</span>";
			}

			function formatresults6()
			{
			  if (!this.timesup) return "<span class='lcdstyle'>"+
				arguments[1]+" <sup>hour"  +(arguments[1]==1?"":"s")+"</sup> "+
				arguments[2]+" <sup>minute"+(arguments[2]==1?"":"s")+"</sup> "+
				arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> left until midnight";
			  // here the time is up:
			  alert("Midnight"); // WILL however block the browser
			  return "<span class='lcdstyle'>Midnight!</span>";
			}

	// put new function here for the 15 second countdown with a 10 second auto restart, please keep code the same as function6 listed above as much as possible so changes are at a minimum

	</script>

	</head>
	<body>


	<div id="countdowncontainer"></div>

	<br>

	<div id="countdowncontainer2"></div>

	<br>

	<div id="countdowncontainer3"></div>

	<br>

	<div id="countdowncontainer4"></div>

	<br>

	<div id="countdowncontainer5"></div>

	<br>

	<div id="countdowncontainer6"></div>

	<br>

	<div id="countdowncontainer7"></div>


	<script type="text/javascript">

	var futuredate=new cdtime("countdowncontainer", "July 18, 2011 13:00:00")
	futuredate.displaycountdown("days", formatresults)


	var currentyear=new Date().getFullYear()
	//dynamically get this Christmas' year value. If Christmas already passed, then year=current year+1
	var thischristmasyear=(new Date().getMonth()>=11 && new Date().getDate()>25)? currentyear+1 : currentyear
	var christmas=new cdtime("countdowncontainer2", "December 25, "+thischristmasyear+" 0:0:00")
	christmas.displaycountdown("days", formatresults2)


	var midnightTonight = new Date();
	midnightTonight.setHours(23,59,59,999);
	var futuredate=new cdtime("countdowncontainer3", midnightTonight.getTime())
	futuredate.displaycountdown("days", formatresults3)


	var midnightTonight = new Date();
	midnightTonight.setHours(23,59,59,999);
	var futuredate=new cdtime("countdowncontainer4", midnightTonight.getTime())
	futuredate.displaycountdown("days", formatresults4)


	var midnightTonight = new Date();
	midnightTonight.setHours(23,59,59,999);
	var futuredate=new cdtime("countdowncontainer5", midnightTonight.getTime())
	futuredate.displaycountdown("days", formatresults5)


	var midnightTonight = new Date();
	midnightTonight.setHours(23,59,59,999);
	var futuredate=new cdtime("countdowncontainer6", midnightTonight.getTime())
	futuredate.displaycountdown("hours", formatresults6)


	<!-- Put new code here for div container 7 which I already made for you above, be sure I can edit x being the time to countdown and y being the time to restart the countdown as I like to change those two often -->

	var midnightTonight = new Date();
	midnightTonight.setSeconds( midnightTonight.getSeconds() + 15 ); //only add the amount of seconds 
	var futuredate=new cdtime("countdowncontainer7", midnightTonight.getTime())
	futuredate.displaycountdown("hours", formatresults)



	</script>

	</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36532440
Hello gurvinder372,

Sure, you can help, the reason I mentioned “mplungjan” was because he already seemed to have this particular JavaScript mastered from the last time he looked at it for me.

Okay, I checked your work and it looks good but a few things were missing which are:

a) I want variable y to be set to 10 seconds as the time it takes for the countdown to start and for the time it takes for the countdown to restart, at the moment I see no variable y for me to edit.

b) I want variable x which I see you made for me to countdown from 15 seconds but the way you have it at the moment it starts from 14 seconds even though I do see you have it set to 15 seconds in the code.

See your code below:

var restartingCountdown = new Date();
restartingCountdown.setSeconds( restartingCountdown.getSeconds() + 15 ); //only add the amount of seconds
var futuredate=new cdtime("countdowncontainer7", restartingCountdown.getTime())
futuredate.displaycountdown("seconds", formatresults7)

Notice I want “countdowncontainer7” and “formatresults7” to stay as I have them and I changed hours to seconds for you as you forgot to do that for me as it will cause you to get a N/A error but I fixed that part for you so don’t worry about that anymore. I also named midnightTonight to restartingCountdown to help me know what the code does better as I have a habit to forget what code does after I look back at it months or years later.

<html>
<head>

<style style="text/css">

.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:yellow;
font: bold 18px MS Sans Serif;
padding: 3px;
}

.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}

</style>

<script type="text/javascript">

/***********************************************
* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this


var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


function formatresults(){
if (this.timesup==false){//if target date/time not yet met
var displaystring=arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until July 18, 2011 13:00:00"
}
else{ //else if target date/time met
var displaystring="Future date is here!"
}
return displaystring
}

function formatresults2(){
if (this.timesup==false){ //if target date/time not yet met
var displaystring="<span class='lcdstyle'>"+arguments[0]+" <sup>days</sup> "+arguments[1]+" <sup>hours</sup> "+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span> left until this Christmas"
}
else{ //else if target date/time met
var displaystring="" //Don't display any text
alert("Christmas is here!") //Instead, perform a custom alert
}
return displaystring
}

function formatresults3(){
  return (this.timesup)?"Midnight!":arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until midnight";
}

function formatresults4(){
if (this.timesup==false){ //if target date/time not yet met
var displaystring="<span class='lcdstyle'>"+arguments[0]+" <sup>days</sup> "+arguments[1]+" <sup>hours</sup> "+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span> left until midnight"
}
else{ //else if target date/time met
var displaystring="<span class='lcdstyle'>Midnight!</span>" //Display text
alert("Midnight!") //Custom alert
}
return displaystring
}

function formatresults5(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[0]+" <sup>day"   +(arguments[0]==1?"":"s")+"</sup> "+
    arguments[1]+" <sup>hour"  +(arguments[1]==1?"":"s")+"</sup> "+
    arguments[2]+" <sup>minute"+(arguments[2]==1?"":"s")+"</sup> "+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> left until midnight";
  // here the time is up:
  alert("Midnight"); // WILL however block the browser
  return "<span class='lcdstyle'>Midnight!</span>";
}

function formatresults6(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[1]+" <sup>hour"  +(arguments[1]==1?"":"s")+"</sup> "+
    arguments[2]+" <sup>minute"+(arguments[2]==1?"":"s")+"</sup> "+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> left until midnight";
  // here the time is up:
  alert("Midnight"); // WILL however block the browser
  return "<span class='lcdstyle'>Midnight!</span>";
}

function formatresults7(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  return "<span class='lcdstyle'>test test test</span>";
}

</script>

</head>
<body>


<div id="countdowncontainer"></div>

<br>

<div id="countdowncontainer2"></div>

<br>

<div id="countdowncontainer3"></div>

<br>

<div id="countdowncontainer4"></div>

<br>

<div id="countdowncontainer5"></div>

<br>

<div id="countdowncontainer6"></div>

<br>

<div id="countdowncontainer7"></div>


<script type="text/javascript">

var futuredate=new cdtime("countdowncontainer", "July 18, 2011 13:00:00")
futuredate.displaycountdown("days", formatresults)


var currentyear=new Date().getFullYear()
//dynamically get this Christmas' year value. If Christmas already passed, then year=current year+1
var thischristmasyear=(new Date().getMonth()>=11 && new Date().getDate()>25)? currentyear+1 : currentyear
var christmas=new cdtime("countdowncontainer2", "December 25, "+thischristmasyear+" 0:0:00")
christmas.displaycountdown("days", formatresults2)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer3", midnightTonight.getTime())
futuredate.displaycountdown("days", formatresults3)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer4", midnightTonight.getTime())
futuredate.displaycountdown("days", formatresults4)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer5", midnightTonight.getTime())
futuredate.displaycountdown("days", formatresults5)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer6", midnightTonight.getTime())
futuredate.displaycountdown("hours", formatresults6)


var restartingCountdown = new Date();
restartingCountdown.setSeconds( restartingCountdown.getSeconds() + 15 ); //only add the amount of seconds
var futuredate=new cdtime("countdowncontainer7", restartingCountdown.getTime())
futuredate.displaycountdown("seconds", formatresults7)

</script>

</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36538360
Hello,

Was anybody able to solve this JavaScript issue for me?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36539112
If no one returns, I'll look in the morning (CET)
0
 

Author Comment

by:Richard Morris
ID: 36541160
Hello mplungjan,

Thank you, you are the greatest ever.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36541816
Ok, looking now
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36542226
Hmm, not that simple :(
0
 

Author Comment

by:Richard Morris
ID: 36545368
Hello mplungjan,

Any luck figuring it out?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36545385
I tried. I was also very busy. I'll try some more if noone else does tomorrow
0
 

Author Comment

by:Richard Morris
ID: 36545570
Hello mplungjan,

Thank you, I have seen this script before but in FLASH so I am not able to show you an example of it but I do know for sure that it can be done.

I’ll wait for you to crack it as you seem to be able to make any JavaScript work from what I’ve seen of your previous work nothing can stop you because you have an uncanny ability to cut through JavaScript code like a hot knife through butter, a skill I wish I had too but don’t.

Have a wonderful night my friend.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36545765
You too.

I will take the original code and not try to hack what Gurvinder did

If he returns he can finish what he did. I will take it from scratch
0
 

Author Comment

by:Richard Morris
ID: 36546265
I checked to see what gurvinder372 did and he changed one line of code and only the part in the brackets so it wasn’t that extensive and believe it or not what he changed was something you did from a few months ago for the midnight countdown which works very well might I add.

Here is what he made:

var restartingCountdown = new Date();
restartingCountdown.setSeconds( restartingCountdown.getSeconds() + 15 ); //only add the amount of seconds
var futuredate=new cdtime("countdowncontainer7", restartingCountdown.getTime())
futuredate.displaycountdown("seconds", formatresults7)

However this is all that he changed from the original, the rest was the same as before:

restartingCountdown.setSeconds( restartingCountdown.getSeconds() + 15 ); //only add the amount of seconds

So if you can’t use this line above, feel free to start from scratch, personally I do not know if that line of code is helpful or not with what we are trying to do as I’m not a JavaScript mastermind like you are.

I’m not sure how you do it, but whenever you do JavaScript they always amaze me compared to JavaScript’s I have seen elsewhere, you seem to have another layer of knowledge that is just not tangible elsewhere.

Not sure what time zone you’re in, I’m assuming European since you said you’re going to bed, regardless have a wonderful sleep, you deserve it.

See you tomorrow.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36547262
Thanks for the kind words.
I am in Holland and it is now 6am
I will resume my work on this in a few hours. I did not compare the two scripts so I assumed more changes. It should be possible.
0
 

Author Comment

by:Richard Morris
ID: 36547288
Good morning dear friend,

Holland sounds like a wonderful place to live.

Based on it being 6:00 a.m. that means you are five hours ahead of me.

Thank God it should be possible, can’t wait to test it, I think I’ll stay up tonight to see the script as otherwise I’d just go to bed.

Talk soon.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36547852
Arrgh.

I HAD fixed it. I just repeated the count down after 10 milliseconds instead of 10 seconds so I thought it did not pause

Here is the code:


var x = 15; // countdown - it will countdown from 14 to 0, which is 15 seconds
var y = 10; // repeat

function formatresults7(){
  if (!this.timesup) return "<span class='lcdstyle'>"+arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span>";
}

function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer7", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults7, repeat)
}
repeatedCountDown(x,y); // x is seconds, y is repeat

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36548262
Wow!!! That sure is amazing coding, very neat and clean which I really appreciate. You should teach others as I can’t recall seeing anybody write Java so well.

I did some tests and found two things however which are:

1) I assumed the restarting at 10 seconds would also mean the countdown starts 10 seconds after the page loads but now see that is not the case, so I made a z variable for the time to start but it isn’t working for me as you’ll see in the code below.

2) I see when I want more than one restarting countdown running on my page one of them will fail when there are two together, is there a workaround such as naming something differently due to a conflict perhaps?

Functions 8 and 9 are the two in question, 8 is the one you just did which now fails due to me adding 9 and 9 is the one I’m trying to add var z to for the start time after the browser loads for the countdown to kick into gear.

Hope we can make this work as we are so very close now to a complete success.

Here is what I have below:

<html>
<head>

<style style="text/css">

.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:yellow;
font: bold 18px MS Sans Serif;
padding: 3px;
}

.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}

</style>

<script type="text/javascript">

/***********************************************
* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this


var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


function formatresults(){
if (this.timesup==false){//if target date/time not yet met
var displaystring=arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until July 18, 2011 13:00:00"
}
else{ //else if target date/time met
var displaystring="Future date is here!"
}
return displaystring
}


function formatresults2(){
if (this.timesup==false){ //if target date/time not yet met
var displaystring="<span class='lcdstyle'>"+arguments[0]+" <sup>days</sup> "+arguments[1]+" <sup>hours</sup> "+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span> left until this Christmas"
}
else{ //else if target date/time met
var displaystring="" //Don't display any text
alert("Christmas is here!") //Instead, perform a custom alert
}
return displaystring
}


function formatresults3(){
  return (this.timesup)?"Midnight!":arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until midnight";
}


function formatresults4(){
if (this.timesup==false){ //if target date/time not yet met
var displaystring="<span class='lcdstyle'>"+arguments[0]+" <sup>days</sup> "+arguments[1]+" <sup>hours</sup> "+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span> left until midnight"
}
else{ //else if target date/time met
var displaystring="<span class='lcdstyle'>Midnight!</span>" //Display text
alert("Midnight!") //Custom alert
}
return displaystring
}


function formatresults5(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[0]+" <sup>day"   +(arguments[0]==1?"":"s")+"</sup> "+
    arguments[1]+" <sup>hour"  +(arguments[1]==1?"":"s")+"</sup> "+
    arguments[2]+" <sup>minute"+(arguments[2]==1?"":"s")+"</sup> "+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> left until midnight";
  // here the time is up:
  alert("Midnight"); // WILL however block the browser
  return "<span class='lcdstyle'>Midnight!</span>";
}


function formatresults6(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[1]+" <sup>hour"  +(arguments[1]==1?"":"s")+"</sup> "+
    arguments[2]+" <sup>minute"+(arguments[2]==1?"":"s")+"</sup> "+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> left until midnight";
  // here the time is up:
  alert("Midnight"); // WILL however block the browser
  return "<span class='lcdstyle'>Midnight!</span>";
}


function formatresults7(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  return "<span class='lcdstyle'>test test test</span>";
}


var x = 15; // countdown - it will countdown from 14 to 0, which is 15 seconds
var y = 10; // repeat

function formatresults8(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span>";
}


var x = 21; // countdown - it will countdown from 20 to 0, which is 21 seconds
var y = 10; // repeat
var z = 10; // start

function formatresults9(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span>";
}

</script>

</head>
<body>


<div id="countdowncontainer"></div>

<br>

<div id="countdowncontainer2"></div>

<br>

<div id="countdowncontainer3"></div>

<br>

<div id="countdowncontainer4"></div>

<br>

<div id="countdowncontainer5"></div>

<br>

<div id="countdowncontainer6"></div>

<br>

<div id="countdowncontainer7"></div>

<br>

<div id="countdowncontainer8"></div>

<br>

<div id="countdowncontainer9"></div>


<script type="text/javascript">

var futuredate=new cdtime("countdowncontainer", "July 18, 2011 13:00:00")
futuredate.displaycountdown("days", formatresults)


var currentyear=new Date().getFullYear()
//dynamically get this Christmas' year value. If Christmas already passed, then year=current year+1
var thischristmasyear=(new Date().getMonth()>=11 && new Date().getDate()>25)? currentyear+1 : currentyear
var christmas=new cdtime("countdowncontainer2", "December 25, "+thischristmasyear+" 0:0:00")
christmas.displaycountdown("days", formatresults2)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer3", midnightTonight.getTime())
futuredate.displaycountdown("days", formatresults3)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer4", midnightTonight.getTime())
futuredate.displaycountdown("days", formatresults4)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer5", midnightTonight.getTime())
futuredate.displaycountdown("days", formatresults5)


var midnightTonight = new Date();
midnightTonight.setHours(23,59,59,999);
var futuredate=new cdtime("countdowncontainer6", midnightTonight.getTime())
futuredate.displaycountdown("hours", formatresults6)


var restartingCountdown = new Date();
restartingCountdown.setSeconds( restartingCountdown.getSeconds() + 15 ); //only add the amount of seconds
var futuredate=new cdtime("countdowncontainer7", restartingCountdown.getTime())
futuredate.displaycountdown("seconds", formatresults7)


function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer8", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults8, repeat)
}
repeatedCountDown(x,y); // x is seconds, y is repeat


function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer9", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults9, repeat)
}
repeatedCountDown(x,y); // x is seconds, y is repeat, z is start

</script>

</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36551718
Sorry I will need more time to make that work

If you change the timeouts to save in an array, you can have two functions until I get around to streamlining it

var tIds=[];
function formatresults8(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  tIds[tIds.length]=setTimeout(function() { repeatedCountDown(x1,y1,z1)},z1*1000);
  return "<span class='lcdstyle'>This will repeat in "+z1+" seconds</span>";
}
function formatresults9(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  tIds[tIds.length]=setTimeout(function() { repeatedCountDown(x2,y2,z2)},z2*1000);
  return "<span class='lcdstyle'>This will repeat in "+z2+" seconds</span>";
}
0
 

Author Comment

by:Richard Morris
ID: 36553214
That looks interesting.

My main concern with this now is allowing it to start 10 seconds after the page loads up, any luck on finding a solution?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36553281
Sure - if only one, change my old code from

repeatedCountDown(x,y); // x is seconds, y is repeat
to

var tId = setTimeout(function() {
  repeatedCountDown(x,y); // x is seconds, y is repeat
},10000);
0
 

Author Comment

by:Richard Morris
ID: 36555607
I’m lost, I tried to use what you gave me but nothing works.

I will include the code below, here are some issues:

1) These three countdowns won’t run at the same time, just the last one in the list.

2) Still won’t start 10 seconds after the browser loads, not sure where the z variable goes for the start time after the page loads.

3) The seconds being counted down sometimes shows .999 after them randomly, needs to be fixed as my template is tight and I don’t have room for .999 on the end of my seconds plus it looks bad like that.

4) Sometimes the seconds flash like they have a glitch, not sure why and then during the 10 seconds nothing is suppose to be happening sometimes random seconds just start to flash.

Please send the corrected JavaScript in full as I’m not good at using bits of it and knowing where to put the bits in with the rest as you can see I made it extremely buggy to the max as I’m not good with JavaScript.

<html>
<head>

<style style="text/css">

.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:yellow;
font: bold 18px MS Sans Serif;
padding: 3px;
}

.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}

</style>

<script type="text/javascript">

/***********************************************
* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this


var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


var x = 21; // countdown - it will countdown from 20 to 0, which is 21 seconds
var y = 10; // repeat
var z = 10; // start

function formatresults9(){
  if (!this.timesup) return "<a href='www.test.com'><span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span>";
}


var x1 = 21; // countdown - it will countdown from 20 to 0, which is 21 seconds
var y1 = 10; // repeat
var z1 = 10; // start

var tIds=[];
function formatresults10(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  tIds[tIds.length]=setTimeout(function() { repeatedCountDown(x1,y1,z1)},z1*1000);
  return "<span class='lcdstyle'>This will repeat in "+y1+" seconds</span>";
}


var x2 = 21; // countdown - it will countdown from 20 to 0, which is 21 seconds
var y2 = 10; // repeat
var z2 = 10; // start

function formatresults11(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  tIds[tIds.length]=setTimeout(function() { repeatedCountDown(x2,y2,z2)},z2*1000);
  return "<span class='lcdstyle'>This will repeat in "+y2+" seconds</span>";
}

</script>

</head>
<body>


<div id="countdowncontainer9"></div>

<br>

<div id="countdowncontainer10"></div>

<br>

<div id="countdowncontainer11"></div>


<script type="text/javascript">

function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer9", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults9, repeat)
}
repeatedCountDown(x,y); // x is seconds, y is repeat, z is start


function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer10", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults10, repeat)
}
var tId = setTimeout(function() {
  repeatedCountDown(x1,y1); // x1 is seconds, y1 is repeat, z1 is start
},10000);


function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer11", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults11, repeat)
}
var tId = setTimeout(function() {
  repeatedCountDown(x2,y2); // x2 is seconds, y2 is repeat, z2 is start
},10000);

</script>

</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36555939
As I mentioned you can only call one of them with the code I sent you last.

I will have to rewrite the code to handle multiple timers each with separate starting times.

It will not be very simple
0
 

Author Comment

by:Richard Morris
ID: 36558959
Oh, one restarting countdown timer is okay then, it just took me a bit to figure out what you meant as this is all new to me and I mixed it up a bit but now believe I have it sorted out.

I will include the code below as you originally had it with the change you last gave me, here are some issues I found:

1) The seconds being counted down sometimes shows .999 after them randomly, needs to be fixed as my template is tight and I don’t have room for .999 on the end of my seconds plus it looks bad like that.

2) Is this a cross browser compliant script as I plan to put it on a busy website soon and would like to know if there is anywhere it should be optimized first?

3) Not sure where the z variable goes for the start time after the page loads? It appears you hardcoded the start time after the page loads which is fine if that makes it more stable since I can change it from there assuming I remember what is what. If you notice I had “var z = 10; // start” and “z is start” but did not know how to make it work. You can leave it without the z var if that makes it more stable, otherwise I’d rather have the z var so I can change it fast with little thought needed.

Please send the corrected JavaScript as it looks like we’re almost done, all that is left is making it stable so I don’t get that .999 after my seconds randomly all of the time.

Thank you for everything my friend, you never stop amazing me.

<html>
<head>

<style style="text/css">

.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:yellow;
font: bold 18px MS Sans Serif;
padding: 3px;
}

.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}

</style>

<script type="text/javascript">

/***********************************************
* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this


var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


var x = 21; // countdown - it will countdown from 20 to 0, which is 21 seconds
var y = 10; // repeat

function formatresults(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span>";
}

</script>

</head>
<body>


<div id="countdowncontainer"></div>


<script type="text/javascript">

function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults, repeat)
}
var tId = setTimeout(function() {
  repeatedCountDown(x,y); // x is seconds, y is repeat
},10000);

</script>

</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36559031
Ah, you can change
,10000);
 to
,z*1000) ;

and have
var z=10; // seconds

if you want
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36559087
I cannot guess why you would get 999

For now change

var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))


to
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (secondfield>59) secondField = 0;
0
 

Author Comment

by:Richard Morris
ID: 36559093
Update made with updated code included below but still have two issues:

1) The seconds being counted down oftentimes shows .999 after them randomly, needs to be fixed as my template is tight and I don’t have room for .999 on the end of my seconds plus it looks bad like that.

2) Is this a cross browser compliant script as I plan to put it on a busy website soon and would like to know if there is anywhere it should be optimized first?

Please send the corrected JavaScript as it looks like we’re almost done, all that is left is making it stable so I don’t get that .999 after my seconds randomly all of the time.

Thank you for everything my friend because you are the very definition of a JavaScript expert!

<html>
<head>

<style style="text/css">

.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:yellow;
font: bold 18px MS Sans Serif;
padding: 3px;
}

.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}

</style>

<script type="text/javascript">

/***********************************************
* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this


var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


var x = 21; // countdown - it will countdown from 20 to 0, which is 21 seconds
var y = 10; // repeat
var z = 10; // start

function formatresults(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span>";
}

</script>

</head>
<body>


<div id="countdowncontainer"></div>


<script type="text/javascript">

function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults, repeat)
}
var tId = setTimeout(function() {
  repeatedCountDown(x,y); // x is countdown, y is repeat
},z*1000); // z is start

</script>

</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36559097
Sorry, I posted too fast as you were two minutes ahead of me in your post.

I will do what you said and post back to you as fast as I can.
0
 

Author Comment

by:Richard Morris
ID: 36559229
I still have the .999 showing after my seconds, please help me.

Updated code with your last edit showing below:

<html>
<head>

<style style="text/css">

.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:yellow;
font: bold 18px MS Sans Serif;
padding: 3px;
}

.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}

</style>

<script type="text/javascript">

/***********************************************
* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this


var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (secondfield>59) secondField = 0;
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


var x = 21; // countdown - it will countdown from 20 to 0, which is 21 seconds
var y = 10; // repeat
var z = 10; // start

function formatresults(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span>";
}

</script>

</head>
<body>


<div id="countdowncontainer"></div>


<script type="text/javascript">

function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults, repeat)
}
var tId = setTimeout(function() {
  repeatedCountDown(x,y); // x is countdown, y is repeat
},z*1000); // z is start

</script>

</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36559462
Very strange - I need to know which of the counters and at what time please (assuming it is not truly random)
0
 

Author Comment

by:Richard Morris
ID: 36559624
Well there is only one countdown timer but if you mean out of vars x, y and z for the countdown I will say that it is var x is the one with .999 after my seconds because vars y and z don’t show any seconds on your screen as they should be.

The time is from 19.999 seconds all the way down to 0.999 of a second, when it bugs out like that every second of the var x shows .999 okay.

Example:

19.999 seconds
18.999 seconds
17.999 seconds
16.999 seconds
15.999 seconds
14.999 seconds
13.999 seconds
12.999 seconds
11.999 seconds
10.999 seconds
9.999 seconds
8.999 seconds
7.999 seconds
6.999 seconds
5.999 seconds
4.999 seconds
3.999 seconds
2.999 seconds
1.999 seconds
0.999 of a second

I tested this in IE where it seems to do .999 on the end of my seconds more often than when I tested it in Safari because it seems to do it less often yet both are very random and disturbing.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36559819
Apologies.

There are inconsistencies in the code.
secondfield was defined twice.

Please remove my if (secondfield > 59) ... line and change

  var timediff=(this.targetdate-this.currentTime)/1000; //difference btw target date and current date, in seconds

to

  var timediff=parseInt((this.targetdate-this.currentTime)/1000,10); //difference btw target date and current date, in seconds

I moved some vars around and moved the script to the head:
<html>
<head>

<style style="text/css">

.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:yellow;
font: bold 18px MS Sans Serif;
padding: 3px;
}

.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}

</style>

<script type="text/javascript">

/***********************************************
* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
  var thisobj=this;
  var timediff=parseInt((this.targetdate-this.currentTime)/1000,10); //difference btw target date and current date, in seconds
  if (timediff<0){ //if time is up
    this.timesup=true
    this.container.innerHTML=this.formatresults()
    return
  }
  var oneMinute=60 //minute unit in seconds
  var oneHour=60*60 //hour unit in seconds
  var oneDay=60*60*24 //day unit in seconds
  var dayfield=Math.floor(timediff/oneDay)
  var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
  var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
  var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
  if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
    hourfield=dayfield*24+hourfield
    dayfield="n/a"
  }
  else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
    minutefield=dayfield*24*60+hourfield*60+minutefield
    dayfield=hourfield="n/a"
  }
  else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
    secondfield=timediff
    dayfield=hourfield=minutefield="n/a"
  }
  this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
  setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


var x = 21; // countdown - it will countdown from 20 to 0, which is 21 seconds
var y = 10; // repeat
var z = 3; // start

var tId;
function formatresults(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span>";
}

function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults, repeat)
}
window.onload=function() {
  tId = setTimeout(function() {
    repeatedCountDown(x,y); // x is countdown, y is repeat
  },z*1000); // z is start
}
</script>

</head>
<body>


<div id="countdowncontainer"></div>

</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36560572
Wow, the script is really starting to come together now indeed.

I do not see any .999 errors, been watching for about an hour or two just to be certain.

However now I have a new error which is sometimes the countdown starts at 20 seconds as it should but other times it starts at 19 seconds which it should not do.

This is yet another random occurrence, please help me.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36560602
Ok. Will look a little later. The 999 shall not re-appear
0
 

Author Comment

by:Richard Morris
ID: 36560731
Okay, I will go eat and then I’ll check back shortly.

Strange it starts at 19 seconds when it is programmed to start at 20 seconds, it seems to do this consistently in both IE and Safari so it isn’t a browser error, seems to be an issue right in the JavaScript itself.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36566551
I cannot reproduce this.

The counter is calculating the time instead of just using a counter. That is why you got 999 and in this case may see 19 because it took some time to get to the function that formats the numbers

Try for fun to change to

  var timediff=Math.ceil((this.targetdate-this.currentTime)/1000); //difference btw target date and current date, in seconds  
0
 

Author Comment

by:Richard Morris
ID: 36566883
Your change seems to have fixed it because I can no longer get 19 seconds when it is set to 20 seconds.

However during the night I left the countdown running while sleeping and when I woke up I found this error in IE which reads as follows:

Message: 'thisobj' is null or not an object
Line: 39
Char: 23
Code: 0

Do you know what that means?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36566942
Could be an IE memory leak..

Try changing

setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
to

setTimeout(function(){if (thisobj) thisobj.updateTime(); else alert('Lost track @'+new Date()) }, 1000) //update time every second

and leave it running again
0
 

Author Comment

by:Richard Morris
ID: 36567551
Thank you, I will let this script run throughout the entire night tonight in IE and then I will report my findings to you in the morning dear sir.
0
 

Author Comment

by:Richard Morris
ID: 36571974
Woke up and got this message again:

Message: 'thisobj' is null or not an object
Line: 39
Char: 23
Code: 0

Very strange message and now my timer has frozen, it was working fine before I went to bed but it froze during the night sometime.

I can refresh the page to unfreeze the timer but that kind of defeats the purpose, anyway to unfreeze the timer so that it stops getting that error I listed above?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36573584
I ran it all night and all day in Safari...
0
 

Author Comment

by:Richard Morris
ID: 36573659
Me too, but the problem is in IE as IE has a status bar at the bottom left which displays the error message, I don’t think other browsers have that so you have to test it with IE please.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36575167
I mean: It did not fail in Safari.

I think it is time to rewrite the script completely. Seems me hacking an existing script is not a good idea

Alternatively we can find another script on the net and re-use the fonts
0
 

Author Comment

by:Richard Morris
ID: 36576415
That’s what I said too, I ran it in Safari and IE both all night long right through till morning, Safari did not fail but IE did fail.

How I performed this test was I had two browsers opened and running on my taskbar all through the night at the same time so I could test both browsers together.

If you feel a rewrite is in order then perhaps you are correct.

The script seemed to be almost show time ready if not for IE throwing up an error.

Yes, I want the ability to use CSS, is there away to write the script to be the exact same as it is now minus the IE error?

Perhaps just shorten up the code but leave all functionally exactly as is, I find JavaScript programs that are too long in size tend to be buggy.

Best to keep the JavaScript code short and neat for sure is what I always heard.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36578419
I'll look and see if there is some obvious issue with ie
0
 

Author Comment

by:Richard Morris
ID: 36578962
Thank you.

I ran the test again and got the same error in IE yet again.

Let me know if a solution is found my friend.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36579169
try this.

I removed the date object from the inside loop and only use milliseconds now
<html>
<head>

<style style="text/css">

.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:yellow;
font: bold 18px MS Sans Serif;
padding: 3px;
}

.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}

</style>

<script type="text/javascript">

/***********************************************
* Dynamic Countdown script- © Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function cdtime(container, targetdate){
  if (!document.getElementById || !document.getElementById(container)) return;
  this.container=document.getElementById(container);
  this.currentTime=new Date().getTime();
  this.targetdate=new Date(targetdate).getTime();
  this.timesup=false;
  this.updateTime();
}

cdtime.prototype.updateTime=function(){
  var thisobj=this;
  this.currentTime+=1000; // one second
  setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
  this.baseunit=baseunit;
  this.formatresults=functionref;
  this.showresults();
}

cdtime.prototype.showresults=function(){
  var thisobj=this;
  var timediff=Math.ceil((this.targetdate-this.currentTime)/1000); //difference btw target date and current date, in seconds  
  if (timediff<0){ //if time is up
    this.timesup=true
    this.container.innerHTML=this.formatresults()
    return
  }
  var oneMinute=60 //minute unit in seconds
  var oneHour=60*60 //hour unit in seconds
  var oneDay=60*60*24 //day unit in seconds
  var dayfield=Math.floor(timediff/oneDay)
  var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
  var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
  var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
  if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
    hourfield=dayfield*24+hourfield
    dayfield="n/a"
  }
  else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
    minutefield=dayfield*24*60+hourfield*60+minutefield
    dayfield=hourfield="n/a"
  }
  else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
    secondfield=timediff
    dayfield=hourfield=minutefield="n/a"
  }
  this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
  setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


var x = 21; // countdown - it will countdown from 20 to 0, which is 21 seconds
var y = 10; // repeat
var z = 3; // start

var tId;
function formatresults(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> test test test";
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span>";
}

function repeatedCountDown(seconds,repeat) {
  var restartingCountdown = new Date();
  restartingCountdown.setSeconds( restartingCountdown.getSeconds() + seconds ); //only add the amount of seconds
  var futuredate=new cdtime("countdowncontainer", restartingCountdown.getTime());
  futuredate.timesup=false;
  futuredate.displaycountdown("seconds", formatresults, repeat)
}
window.onload=function() {
  tId = setTimeout(function() {
    repeatedCountDown(x,y); // x is countdown, y is repeat
  },z*1000); // z is start
}
</script>

</head>
<body>


<div id="countdowncontainer"></div>

</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36579992
Thank you dear friend,

I will let the script run again tonight, it takes about 8 hours for the script to pull up an error in IE while my computer is in sleep mode.

Thus I can only run the test while I sleep too since I use the computer nonstop every day.

I will report my findings back to you tomorrow morning, hopefully all works out well this time.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36580036
I'll do the same.

I do not really see why else could be the problem...
0
 

Author Comment

by:Richard Morris
ID: 36586187
How did your test go last night good sir?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36586324
Apologies, my work pc locked up sometime overnight because I had to leave in a hurry and left too many processes running so no definitive result.

I can try again today. Did you have any luck?

I have now changed the test to

var counter = 1;
function formatresults(){
  if (!this.timesup) return "<span class='lcdstyle'>"+
    arguments[3]+" <sup>second"+(arguments[3]==1?"":"s")+"</sup></span> Test #"+counter;
  // here the time is up:
  setTimeout(function() { repeatedCountDown(x,y)},y*1000);
  return "<span class='lcdstyle'>This will repeat in "+y+" seconds</span> which will be Test #"+(counter++);
}
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36586347
PS: Actually it would run over the weekend
0
 

Author Comment

by:Richard Morris
ID: 36587038
Yes, it ran all night just fine for me, no error so maybe you fixed it?

But if you want to run it for the entire weekend then that would be an even better test as my test was only an overnight test, not a full weekend test as you have proposed.

The test only works when the computer is sleeping, if the computer doesn’t sleep then the timer will not make an error in IE.

I will run the script again tonight to see if an error appears because sometimes errors don’t always appear the first night and require several sequential tests in order to be certain all errors have dissipated.

See you tomorrow kind sir.
0
 

Author Comment

by:Richard Morris
ID: 36592026
Hello,

I just got this error in IE after about a 9 hour test:

Message: 'thisobj' is null or not an object
Line: 39
Char: 25
Code: 0
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36592143
That sucks. I'll investigate
0
 

Author Comment

by:Richard Morris
ID: 36592151
Thank you good sir, I am confident you will find the solution to this IE error.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36593001
I am suspicious of having

setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second

inside a prototype rewrite


0
 

Author Comment

by:Richard Morris
ID: 36593117
Sounds good to me, you’re the man, if you can’t make this script work than nobody can.
0
 

Author Comment

by:Richard Morris
ID: 36593418
I am standing by to test your next version of the script for another overnight test.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36593529
Can you try changing

cdtime.prototype.updateTime=function(){
  var thisobj=this;
  this.currentTime+=1000; // one second
  setTimeout(function(){
    thisobj.updateTime();
    delete thisobj; // allow GC
  }, 1000) //update time every second
}
0
 

Author Comment

by:Richard Morris
ID: 36593647
Done, I will report my findings in the morning, hope it works.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36594437
Can you run another test where you change
delete thisobj;

to

thisobj=null;
0
 

Author Comment

by:Richard Morris
ID: 36595190
Change made, will run another test again tonight.

Just so you know last night’s test failed so let’s pray for tonight’s test to be a successful one.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36595196
:( - how annoying
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

 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36595246
Here is an alternative one
http://www.ricocheting.com/code/javascript/html-generator/countdown-timer

If you add the lines from the comment, it will repeat
0
 

Author Comment

by:Richard Morris
ID: 36596013
That looks like a good script, nice and stable looking I think.

But I need it to do the following:

1) Load the countdown x seconds after the page loads, example 5 seconds

2) Countdown x seconds, example 15 seconds

3) Restart after x seconds, example 5 seconds

I don’t see anywhere in the script to add my three settings, please help me.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36597030
I'll look
0
 

Author Comment

by:Richard Morris
ID: 36598608
I tested the latest version of the first script you edited and it failed again in IE.

Any luck adding my three settings to the new script?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36598966
Here is a working but not super efficient version -

I will get back with a nicer one later but please test this in IE


<html>
<head>
<script type="text/javascript">
//######################################################################################
// Author: ricocheting.com
// Version: v2.0
// Date: 2011-03-31
// Description: displays the amount of time until the "dateFuture" entered below.

// NOTE: the month entered must be one less than current month. ie; 0=January, 11=December
// NOTE: the hour is in 24 hour format. 0=12am, 15=3pm etc
// format: dateFuture1 = new Date(year,month-1,day,hour,min,sec)
// example: dateFuture1 = new Date(2003,03,26,14,15,00) = April 26, 2003 - 2:15:00 pm



// TESTING: comment out the line below to print out the "dateFuture" for testing purposes
//document.write(dateFuture +"<br />");
//###################################
//nothing beyond this point
function GetCount(ddate,iid){
	dateNow = new Date();	//grab current date
	amount = ddate.getTime() - dateNow.getTime();	//calc milliseconds between dates
	delete dateNow;

	// if time is already past
	if(amount < 0){
		document.getElementById(iid).innerHTML="Now!"
		if (myDates[iid].repeat) {
      myDates[iid].tId = setTimeout(funcs[iid],myDates[iid].delay*1000);
      document.getElementById(iid).innerHTML="This will repeat in "+myDates[iid].delay;
    } 
	}
	// else date is still good
	else{
		secs=0;out="";

		amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

		secs=Math.floor(amount);//seconds

		out += secs +" "+((secs==1)?"sec":"secs")+", ";
		out = out.substr(0,out.length-2);
		document.getElementById(iid).innerHTML=out;
		myDates[iid].tId = setTimeout(function(){GetCount(ddate,iid)}, 1000);
	}
}

  var myDates = {
    d0: {
      durationInSecs: 5, 
      delay:0,
      repeat:false,
      tId:""
    }, 
    d1: { 
      durationInSecs: 10, 
      delay:3,
      repeat:true,
      tId:""
    }
  }
  var funcs = {};

window.onload=function(){
  // the below could be done in a loop, if I was better in closures
  setTimeout(function() {
    funcs["d0"] = function() {
      var myDate = myDates["d0"];    
      var dateFuture0 = new Date();
      dateFuture0.setSeconds(dateFuture0.getSeconds()+myDate.durationInSecs);
      GetCount(dateFuture0,"d0");    
    }
    funcs["d0"]();
  },myDates["d0"].delay*1000);
  // ---------------
  setTimeout(function() {
    funcs["d1"] = function() {
      var myDate = myDates["d1"];
      var dateFuture1 = new Date();
      dateFuture1.setSeconds(dateFuture1.getSeconds()+myDate.durationInSecs);
      GetCount(dateFuture1,"d1");    
    }
    funcs["d1"]();    
  },myDates["d1"].delay*1000);
};
</script>
</head>
<body>
<div>
<span id="d0" style="background-color:red">!!</span>
<span style="float:right¨;background-color:green" id="d1"></span>
</div>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36598971
PS You only need to change
  var myDates = {
    d0: {
      durationInSecs: 5,
      delay:0,
      repeat:false,
      tId:""
    },
    d1: {
      durationInSecs: 10,
      delay:3,
      repeat:true,
      tId:""
    }
  }


and possibly the NOW! text which can also be parametrised
0
 

Author Comment

by:Richard Morris
ID: 36599258
Sorry, this one is hard for me to explain, but let me try to go through all of the issues below:

a) The first 5 second countdown starts at 5 seconds but then goes to 3 seconds because it skips over the 4 second mark which it should not do.

b) The second countdown starts when the first countdown is at 1 second which it should not do, needs to wait for the first countdown to finish.

c) The second countdown goes from 10 to 8 seconds skipping the 9 second mark, other times it starts at the 9 second mark instead of the 10 second mark.

Side note: Not sure why we need the first countdown at all? I just want to delay the second countdown by 5 seconds from the time the page loads which I see the second countdown does already so that means we can just remove the first countdown?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36600754
I assumed you wanted more than one countdown

By all means delete one
0
 

Author Comment

by:Richard Morris
ID: 36600791
I’m not sure what I need to delete to make it just one countdown?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36600854
Just remove
  d0: {
      durationInSecs: 5,
      delay:0,
      repeat:false,
      tId:""
    },


And the code in the onload pertaining to d0
0
 

Author Comment

by:Richard Morris
ID: 36601017
I now have the extra countdown removed and have spotted two issues which are:

a) The countdown either goes from 10 to 8 seconds skipping the 9 second mark or it starts at the 9 second mark instead of the 10 second mark.

b) The delay after the page loads and the delay between restarting the countdown both seem to use the exact same value however that value is to be two separate values like how it was in the original script that we started with.

<html>
<head>
<script type="text/javascript">
//######################################################################################
// Author: ricocheting.com
// Version: v2.0
// Date: 2011-03-31
// Description: displays the amount of time until the "dateFuture" entered below.

// NOTE: the month entered must be one less than current month. ie; 0=January, 11=December
// NOTE: the hour is in 24 hour format. 0=12am, 15=3pm etc
// format: dateFuture1 = new Date(year,month-1,day,hour,min,sec)
// example: dateFuture1 = new Date(2003,03,26,14,15,00) = April 26, 2003 - 2:15:00 pm



// TESTING: comment out the line below to print out the "dateFuture" for testing purposes
//document.write(dateFuture +"<br />");
//###################################
//nothing beyond this point
function GetCount(ddate,iid){
	dateNow = new Date();	//grab current date
	amount = ddate.getTime() - dateNow.getTime();	//calc milliseconds between dates
	delete dateNow;

	// if time is already past
	if(amount < 0){
		document.getElementById(iid).innerHTML="Now!"
		if (myDates[iid].repeat) {
      myDates[iid].tId = setTimeout(funcs[iid],myDates[iid].delay*1000);
      document.getElementById(iid).innerHTML="This will repeat in "+myDates[iid].delay;
    } 
	}
	// else date is still good
	else{
		secs=0;out="";

		amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

		secs=Math.floor(amount);//seconds

		out += secs +" "+((secs==1)?"sec":"secs")+", ";
		out = out.substr(0,out.length-2);
		document.getElementById(iid).innerHTML=out;
		myDates[iid].tId = setTimeout(function(){GetCount(ddate,iid)}, 1000);
	}
}

  var myDates = {
    d1: { 
      durationInSecs: 10, 
      delay:3,
      repeat:true,
      tId:""
    }
  }
  var funcs = {};

window.onload=function(){
  // the below could be done in a loop, if I was better in closures
  setTimeout(function() {
    funcs["d1"] = function() {
      var myDate = myDates["d1"];
      var dateFuture1 = new Date();
      dateFuture1.setSeconds(dateFuture1.getSeconds()+myDate.durationInSecs);
      GetCount(dateFuture1,"d1");    
    }
    funcs["d1"]();    
  },myDates["d1"].delay*1000);
};
</script>
</head>
<body>
<div>
<span id="d1" style="background-color:red"></span>
</div>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36601076
Ok I'll give you a better one. It is difficult since the calculations are not precise and when they are you may see skipping even when the countdown actually works
0
 

Author Comment

by:Richard Morris
ID: 36601137
I’m looking forward to a better one so that the countdown shows all of the seconds, example:

10
9
8
7
6
5
4
3
2
1
0

It is also important for the countdown to start at 10 rather than 9 when counting down.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36601210
I'll write one from scratch. You only ever want ONE countdown on a page right?
0
 

Author Comment

by:Richard Morris
ID: 36601243
I might want two different countdowns someday in the future, but for now I just need one countdown please.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36709371
Here is the best I think can be done.

<div id="out1">This will start in 5 seconds</div>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {

    var cnt1 = 10;  // number of seconds to count down
    var delay1 = 5; // number of seconds to delay
    var message1 = "This will re-start in "+delay1+" seconds"; // message to show when 0

    var timer1 = new interval(1000, function(){
        document.getElementById('out1').innerHTML = cnt1--;
        if (cnt1 < 0) {
            cnt1 = 10;
            document.getElementById('out1').innerHTML = message1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, delay1*1000);
};
</script>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36709628
This script looks amazing for sure.

However I want to show zero in my countdown, see example below:

10
9
8
7
6
5
4
3
2
1
0

Please help.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36710023
That will be a countdown of 11 seconds

try to change
 document.getElementById('out1').innerHTML = cnt1--;
to

 document.getElementById('out1').innerHTML = --cnt1;

which means you will likely need to change 10 to 11
0
 

Author Comment

by:Richard Morris
ID: 36710071
Changes made but even though I have it set to 11 it still starts at 9 which is missing 10, see changes below:

<html>
<head>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {

    var cnt1 = 11;  // number of seconds to count down
    var delay1 = 5; // number of seconds to delay
    var message1 = "This will re-start in "+delay1+" seconds"; // message to show when 0

    var timer1 = new interval(1000, function(){
        document.getElementById('out1').innerHTML = --cnt1;
        if (cnt1 < 0) {
            cnt1 = 10;
            document.getElementById('out1').innerHTML = message1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, delay1*1000);
};
</script>
</head>
<body>
<div id="out1">This will start in 5 seconds</div>
</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36710145
I'll look later
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36710161
You need cnt1=11 twice

0
 

Author Comment

by:Richard Morris
ID: 36710187
Thank you, I’m standing by for when you're ready.
0
 

Author Comment

by:Richard Morris
ID: 36710426
Got it, now the 10 second mark is no longer missing.

However I see the seconds/second labels are missing which I need to have, example:

10 seconds
9 seconds
8 seconds
7 seconds
6 seconds
5 seconds
4 seconds
3 seconds
2 seconds
1 second
0 seconds

Please help.

<html>
<head>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {

    var cnt1 = 11;  // number of seconds to count down
    var delay1 = 5; // number of seconds to delay
    var message1 = "This will re-start in "+delay1+" seconds"; // message to show when 0

    var timer1 = new interval(1000, function(){
        document.getElementById('out1').innerHTML = --cnt1;
        if (cnt1 < 0) {
            cnt1 = 11;
            document.getElementById('out1').innerHTML = message1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, delay1*1000);
};
</script>
</head>
<body>
<div id="out1">This will start in 5 seconds</div>
</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36710488
Sure change
document.getElementById('out1').innerHTML = --cnt1;

To
--cnt1;
document.getElementById('out1').innerHTML = cnt1 + "second"+(cnt1==1?"":"s");
0
 

Author Comment

by:Richard Morris
ID: 36710635
I got an error, see code below:

<html>
<head>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {

    var cnt1 = 11;  // number of seconds to count down
    var delay1 = 5; // number of seconds to delay
    var message1 = "This will re-start in "+delay1+" seconds"; // message to show when 0

    var timer1 = new interval(1000, function(){
        --cnt;
        document.getElementById('out1').innerHTML = cnt1 + "second"+(cnt==1?"":"s");
        if (cnt1 < 0) {
            cnt1 = 11;
            document.getElementById('out1').innerHTML = message1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, delay1*1000);
};
</script>
</head>
<body>
<div id="out1">This will start in 5 seconds</div>
</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36710704
Sorry I was editing on my phone - append a 1 to cnt both places to get cnt1
0
 

Author Comment

by:Richard Morris
ID: 36710820
I got it.

But now I’m missing a space between the seconds and the word second/s, example:

10seconds should be 10 seconds with a space between the number and the word.

<html>
<head>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {

    var cnt1 = 11;  // number of seconds to count down
    var delay1 = 5; // number of seconds to delay
    var message1 = "This will re-start in "+delay1+" seconds"; // message to show when 0

    var timer1 = new interval(1000, function(){
        --cnt1;
        document.getElementById('out1').innerHTML = cnt1 + "second"+(cnt1==1?"":"s");
        if (cnt1 < 0) {
            cnt1 = 11;
            document.getElementById('out1').innerHTML = message1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, delay1*1000);
};
</script>
</head>
<body>
<div id="out1">This will start in 5 seconds</div>
</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36710973
Ok that you must be able to fix yourself

 cnt1 + "sec

 cnt1 + " sec
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36710983
Here
<html>
<head>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {
    var countdownFrom = 11;
    var delay1 = 5; // number of seconds to delay
    var message1 = "This will re-start in "+delay1+" seconds"; // message to show when 0

    var cnt1 = countdownFrom;
    var timer1 = new interval(1000, function(){
        --cnt1;
        document.getElementById('out1').innerHTML = cnt1 + " second"+(cnt1==1?"":"s");
        if (cnt1 < 0) {
            cnt1 = countdownFrom;
            document.getElementById('out1').innerHTML = message1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, delay1*1000);
};
</script>
</head>
<body>
<div id="out1">This will start in 5 seconds</div>
</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36711154
I got it.

It appears the number of seconds set to delay between the countdown’s restarts is also the same number of seconds set for the wait time for the countdown to first start when the page loads.

I need those two values to be separated so that their times can be different rather than the same.

Example:

5 seconds between restarting each countdown (it does this now which is fine)

3 seconds to wait before the series of countdowns begin (I do not see anywhere to edit that var as it appears to be tied into the restart var, please separate them)

Thank you.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36711214
Okee
<html>
<head>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {
  // only need to change these:
    var countdownFrom1 = 11;
    var initialDelay1 = 3; // number of seconds to delay onload
    var delay1 = 5; // number of seconds to delay between
    var message1 = "This will re-start in "+delay1+" seconds"; // message to show when 0

  //-------------------------------
    var cnt1 = countdownFrom;
    var timer1 = new interval(1000, function(){
        --cnt1;
        document.getElementById('out1').innerHTML = cnt1 + " second"+(cnt1==1?"":"s");
        if (cnt1 < 0) {
            cnt1 = countdownFrom1;
            document.getElementById('out1').innerHTML = message1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, initialDelay1*1000);
};
</script>
</head>
<body>
<div id="out1">This will start in 3 seconds</div>
</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36711274
It gave me an error and did not do anything, please help.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36711636
Missed a 1 again sorry.
<html>
<head>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {
  // only need to change these:
    var countdownFrom1 = 11;
    var initialDelay1 = 3; // number of seconds to delay onload
    var delay1 = 5; // number of seconds to delay between
    var message1 = "This will re-start in "+delay1+" seconds"; // message to show when 0

  //-------------------------------
    var cnt1 = countdownFrom1;
    var timer1 = new interval(1000, function(){
        --cnt1;
        document.getElementById('out1').innerHTML = cnt1 + " second"+(cnt1==1?"":"s");
        if (cnt1 < 0) {
            cnt1 = countdownFrom1;
            document.getElementById('out1').innerHTML = message1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, initialDelay1*1000);
};
</script>
</head>
<body>
<div id="out1">This will start in 3 seconds</div>
</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36711923
I got it.

I see you added one message var but I want all three messages to have a var so I tried to do it myself but it didn’t work for me, please fix as I think I made an error when adding the two new message vars in the code below that I need for this script:

<html>
<head>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {
  // only need to change these:
    var countdownFrom1 = 11;
    var message1 = "In cnt1 + " second"+(cnt1==1?"":"s") message is gone"; // message to show during countdown from
    var initialDelay1 = 3; // number of seconds to delay onload
    var messsag1 = "This will start in "+intialDelay1+" seconds"; // message to show during initial delay
    var delay1 = 5; // number of seconds to delay between
    var message1 = "This will re-start in "+delay1+" seconds"; // message to show during delay

  //-------------------------------
    var cnt1 = countdownFrom1;
    var timer1 = new interval(1000, function(){
        --cnt1;
        document.getElementById('out1').innerHTML = cnt1 + " second"+(cnt1==1?"":"s");
        if (cnt1 < 0) {
            cnt1 = countdownFrom1;
            document.getElementById('out1').innerHTML = message1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, initialDelay1*1000);
};
</script>
</head>
<body>
<div id="out1"></div>
</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36712027
You use the same name. Change the second variable you named message1 to something else
0
 

Author Comment

by:Richard Morris
ID: 36712208
Oh I did that on purpose because when you look below you’ll discover I never programmed out anything to make the two new comment vars work as I’m not sure what to do in order to make them work.

Thus I thought you would name the comment vars with the best names possible according to the code you make for them to work since I wasn’t sure what you would want to call them so I just left it open ended for you to decide upon knowing you would know best what names they should have.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36712302
I'll have a look
0
 

Author Comment

by:Richard Morris
ID: 36712399
Thank you.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36712533
Ok done I hope :)
<html>
<head>
<script type="text/javascript">
function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {
  // only need to change these:
    var countdownFrom1 = 11;
    var initialDelay1 = 3; // number of seconds to delay onload
    var initialMesssage1 = "This will start in "+initialDelay1+" seconds"; // message to show during initial delay
    var delay1 = 5; // number of seconds to delay between
    var restartMessage1 = "This will re-start in "+delay1+" seconds"; // message to show during delay

  //-------------------------------
    document.getElementById('out1').innerHTML=initialMesssage1;

    var cnt1 = countdownFrom1;
    var timer1 = new interval(1000, function(){
        --cnt1;
        document.getElementById('out1').innerHTML = "In "+ cnt1 + " second"+(cnt1==1?"":"s") +" message is gone";
        if (cnt1 < 0) {
            cnt1 = countdownFrom1;
            document.getElementById('out1').innerHTML = restartMessage1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, initialDelay1*1000);
};</script>
</head>
<body>
<div id="out1">This will start in 3 seconds</div>
</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36712799
The script appears to do everything I need it to do.

I will now let the script run overnight in IE to see if it is successful during an overnight run.

Then I will report my findings to you.

Have a wonderful night.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36712888
You too.

0
 

Author Comment

by:Richard Morris
ID: 36717000
I did not get a fail message last night in IE, thus you may proceed with the final optimization of the script so that all of the code is clean rather than in draft form and then I will test the script on my live website to see how it performs along with the rest of my stuff I got on my site.

Thank you.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36718999
Not totally sure on how you want this packaged - I'll clean it up a bit tomorrow morning
0
 

Author Comment

by:Richard Morris
ID: 36719101
I don’t know how to package a JavaScript or what cleaning it entails?

Please do whatever is considered clean since personally I don’t know what a clean JavaScript looks like but I assume there are industry standards that make it clean for public consumption?

I am looking forward to the clean version and am eager to do a test install on my actual site to see how it works because I have a few other JavaScript programs like Google +1 for an example so hopefully they all play well together.

Talk soon.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36719133
I can externalise the bits you cannot change. Give me an hour or so. I need a rest from 12 hours behind a computer
0
 

Author Comment

by:Richard Morris
ID: 36719383
What does externalize mean?

I already see the vars I need to edit are ready for me, so not sure how you can externalize more than that?

I thought cleaning simply meant to check to see that everything is spaced and laid out smoothly, that sort of thing or is that not what cleaning a JavaScript means?

I would clean the JavaScript myself but I don’t know how to space the lines of code properly or maybe an editor does that which I do not have, all I have is notepad.

Once you’re done I am putting this JavaScript between my Meta tags and my CSS as that is where I normally put my JavaScript programs.

Tomorrow is fine too, no pressure dear friend, have an excellent night, you’re the best for sure.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36719501
Here you are

Html

<html>
<head>
<script type="text/javascript" src="mhpcountdown.js"></script>
<script type="text/javascript"> 
// only need to change these - for now set as global vars:
var countdownFrom1   = 11;
var initialDelay1    =  3; // number of seconds to delay onload
var delay1           =  5; // number of seconds to delay between
var initialMesssage1 = "This will start in "+initialDelay1+" seconds"; // message to show during initial delay
var restartMessage1  = "This will re-start in "+delay1+" seconds"; // message to show during delay
var suffix1          = " message is gone"; // text is: In nn seconds message is gone

window.onload = function() { // or in $(document).ready 
  setTimer1();
}
</script>
</head>
<body>
<div id="out1">This will start in 3 seconds</div>
</body>
</html>

Open in new window


Externalised JavaScript

// --- this is to be stored in mhpcountdown.js in the same dir as the html

function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;
    
    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

function setTimer1() {
  //-------------------------------
    document.getElementById('out1').innerHTML=initialMesssage1;
    var cnt1 = countdownFrom1;
    var timer1 = new interval(1000, function(){
        --cnt1;
        document.getElementById('out1').innerHTML = "In "+ cnt1 + " second"+(cnt1==1?"":"s") +suffix1;
        if (cnt1 < 0) {
            cnt1 = countdownFrom1;
            document.getElementById('out1').innerHTML = restartMessage1;
            timer1.stop();
            timer1.start(delay1*1000);
        }
    }, initialDelay1*1000);
}

Open in new window

0
 

Author Comment

by:Richard Morris
ID: 36719667
Thank you, I will set this JavaScript up on my site and then report back to you once I get it working.

Have a terrific night.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 36908357
New and improved. Self contained with as many timers you like
accurate-timers.html
0
 

Author Comment

by:Richard Morris
ID: 37086246
Sorry for the delay in replying back to you.

I studied your new JavaScript and discovered the following:

1. console.log(window) seems to throw up an error in IE, how can this be fixed, can that line just be removed as I see the error vanishes if I remove console.log(window) or does console.log(window) need to be there for some reason?

2. For now I just need a single timer so I edited your script down to one timer but not sure if I did it right, can you check it for me please?

3. I added CSS to the JavaScript but not sure if I did it right as I wasn’t sure what spacing to use, the main line I’m wondering about is: container.innerHTML = formatString(timerobj.countdownMessage,"<span class='test2'>" + cnt + "</span>" + " second"+(cnt==1?"":"s"));

To review all of the changes I have made in full detail please see revisions below and let me know if everything I did is correct, thank you.

<html>
<head>
<style style="text/css">
.test1 {
	color: #333333;
	font: bold 18px/28px Arial, sans-serif;
}
.test2 {
	color: #ff0000;
	font: bold 23px/33px Arial, sans-serif;
}
.test3 {
	font: italic bold 18px/28px Arial, sans-serif;
}
</style>
<script type="text/javascript">
// Timer class (c) 2011 mplungjan javascripts(a)plungjan.name
// built with the help of Davin of SO, SEB. Timer based on Manast's setInterval replacement.
// the script can be externalised easily and only the settings edited by the end user
function Timer() {
  function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
  }
  interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
  };
  interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;

    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
  };
  interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
  };
  function formatString(haystack,needle) {
    return haystack.replace("$1",needle);
  }

  this.setTimer = function(timerobj) {
  //-------------------------------

    var container = document.getElementById(timerobj.container)
    container.innerHTML=formatString(timerobj.initialMessage,timerobj.initialDelay);
    var cnt = timerobj.countdownFrom;
    var timer = new interval(1000, function(){
//       console.log(arguments);
        --cnt;
        container.innerHTML = formatString(timerobj.countdownMessage,"<span class='test2'>" + cnt + "</span>" + " second"+(cnt==1?"":"s"));
        if (cnt < 0) {
            cnt = timerobj.countdownFrom;
            container.innerHTML = formatString(timerobj.restartMessage,timerobj.delay);
            timer.stop();
            timer.start(timerobj.delay*1000);
        }
    }, timerobj.initialDelay*1000);
  }
}

// only necessary to edit below

var mytimers = {
  timer1 :{
    container       : "out1",
    initialDelay    :  3, // number of seconds to delay onload
    countdownFrom   : 11, // number of seconds to countdown
    delay           :  5, // number of seconds to delay between
    initialMessage  : "<span class='test1'>This <span class='test3'>will</span> start in $1 seconds</span>",  // the $1 will contain the initial delay
    countdownMessage: "<span class='test1'>In $1 this message is gone</span>",                                // the $1 will contain the counter
    restartMessage  : "<span class='test1'>This will restart in <span class='test3'>$1</span> seconds</span>" // the $1 will contain the delay
  }
}
window.onload = function() { // or in $(document).ready
  var t = new Timer();
  for (var o in mytimers) t.setTimer(mytimers[o]);
}
console.log(window)
</script>
</head>
<body>
<div id="out1"></div>
</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37086262
Sure remove the console log. Only used to debug. I'll look at the code tomorrow
0
 

Author Comment

by:Richard Morris
ID: 37086290
Excellent, I just removed: console.log(window)

See the change below:

<html>
<head>
<style style="text/css">
.test1 {
	color: #333333;
	font: bold 18px/28px Arial, sans-serif;
}
.test2 {
	color: #ff0000;
	font: bold 23px/33px Arial, sans-serif;
}
.test3 {
	font: italic bold 18px/28px Arial, sans-serif;
}
</style>
<script type="text/javascript">
// Timer class (c) 2011 mplungjan javascripts(a)plungjan.name
// built with the help of Davin of SO, SEB. Timer based on Manast's setInterval replacement.
// the script can be externalised easily and only the settings edited by the end user
function Timer() {
  function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;
    this.start(delay);
  }
  interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
  };
  interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;

    this.timer = setTimeout(function(){
        self.run(new Date);
        self.fn();
    }, nextTick<0 ? 0 : nextTick);
  };
  interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
  };
  function formatString(haystack,needle) {
    return haystack.replace("$1",needle);
  }

  this.setTimer = function(timerobj) {
  //-------------------------------

    var container = document.getElementById(timerobj.container)
    container.innerHTML=formatString(timerobj.initialMessage,timerobj.initialDelay);
    var cnt = timerobj.countdownFrom;
    var timer = new interval(1000, function(){
//       console.log(arguments);
        --cnt;
        container.innerHTML = formatString(timerobj.countdownMessage,"<span class='test2'>" + cnt + "</span>" + " second"+(cnt==1?"":"s"));
        if (cnt < 0) {
            cnt = timerobj.countdownFrom;
            container.innerHTML = formatString(timerobj.restartMessage,timerobj.delay);
            timer.stop();
            timer.start(timerobj.delay*1000);
        }
    }, timerobj.initialDelay*1000);
  }
}

// only necessary to edit below

var mytimers = {
  timer1 :{
    container       : "out1",
    initialDelay    :  3, // number of seconds to delay onload
    countdownFrom   : 11, // number of seconds to countdown
    delay           :  5, // number of seconds to delay between
    initialMessage  : "<span class='test1'>This <span class='test3'>will</span> start in $1 seconds</span>",  // the $1 will contain the initial delay
    countdownMessage: "<span class='test1'>In $1 this message is gone</span>",                                // the $1 will contain the counter
    restartMessage  : "<span class='test1'>This will restart in <span class='test3'>$1</span> seconds</span>" // the $1 will contain the delay
  }
}
window.onload = function() { // or in $(document).ready
  var t = new Timer();
  for (var o in mytimers) t.setTimer(mytimers[o]);
}
</script>
</head>
<body>
<div id="out1"></div>
</body>
</html>

Open in new window

0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 37087111
That looks just fine.

The formatstring is just replacing $1 with whatever is passed to it - in this case the span with the number.
0
 

Author Comment

by:Richard Morris
ID: 37204532
Thank you, glad everything is fine thus far.

I’ve been inspecting this script over the past few weeks watching it countdown and restart and realized it would look a lot better if when the time hits zero the text scrolls down out of the div and the new text scrolls up into the div to replace the text that just scrolled down out of the div.

Example: x = speed to scroll text up and down when the countdowns start and stop.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37205430
Hmm, that is quite a bit of feature creep - I would need to add jQuery to the mix

It would be using the animate feature and would be fast or slow or be given a number for duration.

Let me have a look.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37205602
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37206045
Ps pls remind me why we are counting down to -1 instead of 0
0
 

Author Comment

by:Richard Morris
ID: 37207895
I don’t remember why we are counting down to -1 instead of 0? I remember if we wanted to countdown from 10 to 0 we had to start at 11 since JavaScript is always 1 second slow, maybe that is the reason why but I’m just guessing.

Yes, you have created a very good effect.

However, I want all three lines of text do the effect, example below:

Line 1: Roll down
Line 2: Roll up then down
Line 3: Roll up then down
Line 2: Roll up then down
Line 3: Roll up then down
Line 2: Roll up then down

As you can see it is now in a loop so no point for me to keep typing this loop anymore, the loop should last literally forever or until the user closes their web browser.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37207976
Yes it was just an example. It is not that simple as I thought so I wanted to know if I was on the right track
0
 

Author Comment

by:Richard Morris
ID: 37208631
Well at first I was thinking of scrolling the text right out of the div like a scroll, but then when I seen how you did it I liked it, very contemporary looking.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37208640
Please accept my previous answer as solution and ask a new one with the jQuery fade since we should have some more experts on that.

I would still change cnt<0 to cnt<=0 in the middle if
0
 

Author Closing Comment

by:Richard Morris
ID: 37208966
My expert mplungjan was extremely good to work with, he can figure anything out no matter how hard it is because he is the best JavaScript programmer in the whole entire world.

We are now working on a new text slide effect for this script at:

http://www.experts-exchange.com/Programming/Languages/Scripting/JScript/Q_27469655.html
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37209026
Blush :)
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Why do we like using grid based layouts in website design? Let's look at the live examples of websites and compare them to grid based WordPress themes.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
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…

705 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

13 Experts available now in Live!

Get 1:1 Help Now