PDA

View Full Version : Trigger an Event by Browser Time and not setInterval()



sniperman
01-19-2011, 11:06 AM
I know JavaScript has the capability to read the current time based on a user's computer clock.

I've currently set up a timer which updates a variable every 5 seconds


var gAge = 10;
var _gTimerEvents = [];

var teventid = addTimerEvent('IncAgeCB()', 5000);

function IncAgeCB()
{
gAge = gAge + 10;
alert(gAge);
}

function addTimerEvent(evtCB, durationMs)
{
if (!evtCB || !durationMs)
alert("Error: addTimerEvent:"+evtCB+","+durationMs);

var te = setInterval(evtCB, durationMs);
_gTimerEvents[te] = te;
return te;
}

I also have a timer...


function updateClock ( )
{
var currentTime = new Date ( );

var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );

// Pad the minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

// Choose either "AM" or "PM" as appropriate
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

// Convert the hours component to 12-hour format if needed
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

// Convert an hours component of "0" to "12"
currentHours = ( currentHours == 0 ) ? 12 : currentHours;

// Compose the string for display
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

}

One problem that this approach will encounter is that when a browser is refreshed it will lose its real time updates.

I would like to attempt to include a Cookie Session to store a timestamp as a variable and make the script rely more on using real browser time for a timestamp conditional rather than an interval or timer for a conditional.

I am having trouble in trying to run a timestamp subroutine.