Sunday, November 4, 2007

JavaScript Count Up Timer with Source Code using Interval() Method

Try this count up timer.

00:00:00:000

The source code is like below:

<script language="javascript">
var myInterval;
var count = 0;
var startTime;

function startStopCountUp()
{
if (document.getElementById("btnReset").style.display == 'none')
{
document.getElementById("btnReset").style.display = '';
}
if (document.getElementById("btnCountUp").value == "Pause")
{
StopCountUp();
document.getElementById("btnCountUp").value = "Resume";
}
else
{
startTime = new Date();
myInterval = window.setInterval('StartCountUp()',333);
document.getElementById("btnCountUp").value = "Pause";
}
}

function StartCountUp()
{
var myDate = new Date();
count = myDate - startTime + count;
startTime = myDate;

spanTimer.innerHTML = showDiffTime(count);
}

function StopCountUp()
{
window.clearInterval(myInterval);
}

function ResetCountUp()
{
StopCountUp();
document.getElementById("btnCountUp").value = "Start";
document.getElementById("btnReset").style.display = 'none';
count = 0;
spanTimer.innerHTML = '0';
}

function showDiffTime(diffTime)
{
var miliseconds = diffTime % 1000;
var scratch = Math.floor((diffTime - miliseconds) / 1000);
var seconds = scratch % 60;
scratch = Math.floor((scratch - seconds) / 60);
var minutes = scratch % 60;
scratch = Math.floor((scratch - minutes) / 60);
var hours = scratch % 24;
scratch = Math.floor((scratch - hours) / 24);
var days = scratch;

var displayDiffTime = ""

if (days > 0)
displayDiffTime += days + ' days, ';

if (hours > 9)
displayDiffTime += hours + ':';
else
displayDiffTime += '0' + hours + ':';

if (minutes > 9)
displayDiffTime += minutes + ':';
else
displayDiffTime += '0' + minutes + ':';

if (seconds > 9)
displayDiffTime += seconds + ':';
else
displayDiffTime += '0' + seconds + ':';

if (miliseconds > 99)
displayDiffTime += miliseconds;
else if (miliseconds > 9)
displayDiffTime += '0' + miliseconds;
else
displayDiffTime += '00' + miliseconds;
return displayDiffTime;
}
</script>

<input type="button" name="btnCountUp" value="Start" onClick="startStopCountUp();" ID="btnCountUp">
<input type="button" name="btnReset" value="Reset" onClick="ResetCountUp();" ID="btnReset" style="DISPLAY:none">
<span id="spanTimer" style="font-size: 20px; color: orange;">00:00:00:000</span>

Wednesday, October 31, 2007

JavaScript Timers with setTimeout and setInterval Methods

Here, i would like to share with you how to use the JavaScript's settimeout(), clearTimeout(), setInterval() and clearinterval() methods to set timers and create delayed actions.

setTimeout()

The general syntax of window.setTimeout() method is:

setTimeout(expression, timeout);
where expression is the JavaScript code to run after timeout miliseconds have elapsed.
setTimeout() return a numeric timeout ID that can be used to track the timeout. This is most commonly used with the clearTimeout() method.
After setTimeout() is called, execution of the following script will continue normally. The expression in setTimeout() will be run when pass the timeout period.

For example, the following code sets up an alert box to appear after 3 seconds and disable the button when a button is clicked. After 3 seconds, the alert appears. When click the [ok] button of the alert, the button will enable again.
<script language="javascript">
function alertClickHandler()
{
setTimeout('showAlert()', 3000);
document.getElementById("btnClickMe").disabled = true;
}

function showAlert()
{
alert('3 seconds time out');
document.getElementById("btnClickMe").disabled = false;
}
</script>

<input type="button" name="btnClickMe" id="btnClickMe" value="Click me" onclick="alertClickHandler();" />

Try it! Click the button below and wait 3 seconds.



clearTimeout()

The window.clearTimeout() method is used to cancel a timer before it goes off. It's syntax is:
clearTimeout(timeoutId);
where timeoutId is the timeout ID returned from the setTimeout() method call.

For example, the following code sets up an alert box to appear after 3 seconds when a button is clicked, but the visitor can click the same button before the alert appears and cancel the timeout.
<script language="javascript">
var timeoutID = 0;

function alertTimerClickHandler()
{
if (document.getElementById("btnClick").value == "Try click me!")
{
timeoutID = setTimeout('showAlertTimer()', 3000);
document.getElementById("btnClick").value = "Click me to stop the timer!";
}
else
{
clearTimeout(timeoutID);
document.getElementById("btnClick").value = "Try click me!";
}
}

function showAlertTimer()
{
alert('Time out! You did not stop the timer.');
document.getElementById("btnClick").value = "Try click me!";
}
</script>

<input type="button" name="btnClick" id="btnClick" value="Try click me!" onclick="alertTimerClickHandler();" />

Try it! Click the button below to start the timer and click it again within 3 seconds to cancel it.



setInterval()

The setInterval() function is very same to setTimeout() even the their syntax is similar. It's syntax is:
setInterval(expression, interval);
The difference is setTimeout() triggers expression only once but setInterval() keeps triggering expression again and again unless stop it.

clearInterval()

If want to cancel a setInterval(), call clearInterval() method. It's syntax is like below:
clearInterval(intervalId);
where intervalId is the interval ID returned from the setInterval() method call.

Here's a simple example using both setInterval() and clearInterval. When visitor click the button at below, the following code start to count up and display it until visitor click the button again to stop it.
<script language="javascript">
var intervalID = 0;
var count = 0;

function startCountUp()
{
if (document.getElementById("btnClickInterval").value != "Stop count up!")
{
document.getElementById("divCount").innerHTML = count;
intervalID = setInterval('displayCountUp()', 1000);
document.getElementById("btnClickInterval").value = "Stop count up!";
}
else
{
clearInterval(intervalID);
count = 0;
document.getElementById("btnClickInterval").value = "Restart count up!";
}
}

function displayCountUp()
{
count += 1;
document.getElementById("divCount").innerHTML = count;
}
</script>

<div id="divCount" style="font-size: 20px; color: orange;"></div>
<input type="button" name="btnClickInterval" id="btnClickInterval" value="Start count up!" onclick="startCountUp();" />


Try it! Click the button below to start count up and click it again to stop it.

0