User initiated countdown using Javascript or JQuery

Have to warn you up front I’m pretty green…but I learn quickly, so here we go.

I’m looking to create a user-initiated countdown, without having to enter into a new page. Basically, you click a start button, and it starts counting.

The short story is I am creating an app using JQTouch that you can enter information, and hit start. The information will be saved, plus it will give the timer an end date or just start counting down (the countdown will be the same amount of time for everyone), that it will begin to countdown from. Eventually I’d like to be able to pause the timer as well…so if that’s possible, someone who can help with that would also be appreciated.

Let me know if you need any other info from me.

Hi harlan,

This should get you started, all timed functions in javascript are handled with setTimeout or setInterval.
Have a look at this code and see if it makes sense.


<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8>
  <title>jsTime</title>
</head>
<body>
<p>Time left: <span id="time">30</span> seconds.</p>
<p><a href="#" onclick="play()">Play</a> <a href="#" onclick="pause()">Pause</a></p>
<script>
var time = 30,
timeElement = document.getElementById('time'),
timer = null;
var updateTimer = function() {
  timeElement.innerHTML = time--;
  if (time == 0) {
  	clearInterval(timer);
  }
}
function play() {
	timer = setInterval(updateTimer, 1000);
	return false;
}
function pause() {
	clearInterval(timer);
	return false;
}
</script>
</body>
</html>

Mark…thanks a ton. That definitely gets me started.

A couple of questions though…

The first one is easy. I’m going to want to do the timer in days (or maybe days and hours) rather than seconds. Is changing that as easy as just changing the “var time” element to something larger? It’s going to be a six week countdown.

The second question may not be as easy. I’m going to be implementing this as an iphone app, which will have access to local storage. This may not be the forum to ask this…but it may change how we approach the script. I’m not sure how multitasking will affect this, but basically I’d like this countdown to remember where it is. Obviously no one’s going to keep the app open for six weeks, so I’m curious where I should go with this. Should the timer just set a date…like when you hit start, it enters a date six weeks in the future, then saves that date…so that every time you open the app, it remembers that date and counts down to it? Does that make sense?

Thanks again…

All javascript timed functions are in milliseconds so you’ll need to calculate the other values you need yourself;


var milliseconds = 86400000;
var second = milliseconds / 1000; // 86400
var minute = second / 60; // 1440
var hour = minute / 60; // 24
var day = hour / 24; // 1

Also have a look at the Date functions available in js:
https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date

I would only use javascript to display the timer like in the script above if it’s an iPhone app.

I would load the data from the server when you open the date, and on Play and Pause send the message to the server to update.

All the best,

Ok…this might be just what I need.

Now my green is going to shine through…when you guys say “from the server” you mean from some site I’ve got set up online, correct? If so, this is where it get’s tricky for me. Because I’m doing this for an iphone app, the data for the timer should be saved to local storage. Here’s how I’m doing it for other data on the page:


$(document).ready(function(){
    $('#container form').submit(saveSettings);
    loadSettings();
}
});
function saveSettings() {
    localStorage.goal1 = $('#goal1').val();
    localStorage.goal2 = $('#goal2').val();
    jQT.goBack();
    return false;
}

In the above, when someone clicks the submit button on the form in the container div, it saves goals 1 & 2 to local storage.

What I’d like to have happen is when they click the submit button, it saves the goals and starts the timer. It already does this, but when someone closes the app, it stops the timer. Is there a way, using webgypsy’s code, to save that future date in local storage, then when the app loads, it remembers that date and updates the timer accordingly? I’m almost positive there must be…but this is where my lack of javascript know-how is killing me.

Currently, the submit button looks like this (triggers the code above through the script above, then uses onclick to trigger the timer as well.)


<input type="submit" class="submit" name="action" value="Start!" onclick="play()" />

Thanks again guys…

Perhaps another way to look at this is…when you click start, the script saves a date six weeks in the future. That date gets saved to local storage. Then what displays to the user is “6 weeks, 0 days.”

Then, if the user opens the app three days later, the script will recall that saved date, then tell the user how far it is from that date. e.g. “5 weeks, 4 days”.

Let’s forget hours, minutes, and seconds…I think weeks and days will be perfect.

Still trying to work this out. See if you can follow where I’m at.

I decided to use the tzcd script that webgypsy offered, but a friend and I have made some modifications. It’s still not working. Maybe you guys can see where we’re tripped up.

The original is above in webgypsy’s post…mine is here:

<SCRIPT type="text/javascript">

            // ****  Time Zone Count Down Javascript  **** //
            /*
        Visit http://rainbow.arch.scriptmania.com/scripts/
         for this script and many more
             */

            ////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////

	



            var lab = 'tzcd';    //  The id of the page entry where the timezone countdown is to show
	    // The number of milliseconds in one day
	    var ONE_DAY = 1000 * 60 * 60 * 24

            function start() 
	    {
		loadSettings();
		var goalDate = new Date();
		goalDate.setDate(document.getElementByID("dueDate").value);

		displayTZCountDown(setTZCountDown(goalDate),lab);
	    }

            // **    The start function can be changed if required   **
            window.onload = start;

            ////////// DO NOT EDIT PAST THIS LINE //////////////////


            function setTZCountDown(goalDate)
            {
                var dueDate = new Date();
		var currDate = new Date();

		if(goalDate != null)
			dueDate.setDate(goalDate.getDate());
		else 
			dueDate.setDate(dueDate.getDate() + 42)
		document.getElementByID("dueDate").value = dueDate.getDate();     

		var daysLeft = daysBetween(dueDate.getDate(), currDate.getDate());
		displayTZCountDown(daysLeft, lab);
            }

            function displayTZCountDown(daysLeft, tzcd)
            {
                if (countdown < 0) 
			document.getElementById(tzcd).innerHTML = "Sorry, you are too late.";
                else 
		{
                    document.getElementById(tzcd).innerHTML = getTimeString(daysLeft);
                    setTimeout('displayTZCountDown('+(daysLeft-1)+',\\''+tzcd+'\\');',ONE_DAY);
                }
            }

	    function getTimeString(days) 
	    {
		var timeString = "";
		timeString = (Math.floor(days/7)) + " days";
		timeString = (days % 7) + " weeks, " + timeString;
		return timeString;
	    }

	    function daysBetween(date1, date2)
	    {
		    // Convert both dates to milliseconds
		    var date1_ms = date1.getTime()
		    var date2_ms = date2.getTime()
		
		    // Calculate the difference in milliseconds
		    var difference_ms = Math.abs(date1_ms - date2_ms)
		    
		    // Convert back to days and return
		    return Math.round(difference_ms/ONE_DAY)
   	    }
</SCRIPT>

Then, to add the dueDate to local storage:

function saveSettings() {
    localStorage.goal1 = $('#goal1').val();
    localStorage.goal2 = $('#goal2').val();
    localStorage.dueDate = $('#dueDate').val();
    jQT.goBack();
    return false;
}

The HTML for displaying the deadline is here: (it should go between the “tzcd” span class)


		<table id="deadlinetable">
			<tr>
				<td><p align="right">Deadline</p></td>
				<td><p align="left"><span id="tzcd"></span></p></td>
			</tr>
		</table>

Any help would be greatly appreciated!

Wow…I feel like a schizophrenic…talking to people who aren’t there. Webgypsy’s post isn’t there anymore…just disappeared.

Nonetheless, here’s the original tzdc code.

<SCRIPT type="text/javascript">

// ****  Time Zone Count Down Javascript  **** //
/*
Visit http://rainbow.arch.scriptmania.com/scripts/
 for this script and many more
*/

////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////

var month = '*';     //  '*' for next month, '0' for this month or 1 through 12 for the month 
var day = '1';       //  Offset for day of month day or + day  
var hour = 0;        //  0 through 23 for the hours of the day
var tz = -5;         //  Offset for your timezone in hours from UTC
var lab = 'tzcd';    //  The id of the page entry where the timezone countdown is to show

function start() {displayTZCountDown(setTZCountDown(month,day,hour,tz),lab);}

    // **    The start function can be changed if required   **
window.onload = start;

////////// DO NOT EDIT PAST THIS LINE //////////////////

function setTZCountDown(month,day,hour,tz) 
{
var toDate = new Date();
if (month == '*')toDate.setMonth(toDate.getMonth() + 1);
else if (month > 0) 
{ 
if (month <= toDate.getMonth())toDate.setYear(toDate.getYear() + 1);
toDate.setMonth(month-1);
}
if (day.substr(0,1) == '+') 
{var day1 = parseInt(day.substr(1));
toDate.setDate(toDate.getDate()+day1);
} 
else{toDate.setDate(day);
}
toDate.setHours(hour);
toDate.setMinutes(0-(tz*60));
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd) 
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "Sorry, you are too late."; 
else {var secs = countdown % 60; 
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60; 
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = days + " day" + (days == 1 ? '' : 's') + ' + ' +hours+ 'h : ' +mins+ 'm : '+secs+'s';
setTimeout('displayTZCountDown('+(countdown-1)+',\\''+tzcd+'\\');',999);
}
}
</SCRIPT>
<p><font face="arial" size="-2">The countdown script at </font><br><font face="arial, helvetica" size="-2"><a href="http://rainbow.arch.scriptmania.com/scripts/">Rainbow Arch</a></font></p>