First of all, you won't want to use
document.write(timeLeft) as this will keep adding to the string instead of updating it.
Instead put this function in the head of the document and update the string using the
DOM (e.g
document.getElementById('countdown').firstChild.da ta = timeLeft)
There's also no need to assign your setTimeout to a variable. Just call it at the end of your function.
Here's a complete script that works (Tested in FF 2.0 and IE7).
- HTML: Select all
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
// <![CDATA[
function timer(){
var today = new Date();
var timeNow = today.getTime();
var target = new Date("23 July, 2007");
var timeTarget = target.getTime();
seconds = Math.floor((timeTarget - timeNow) / 1000);
secs = String(seconds % 60);
minutes = Math.floor(seconds / 60);
mins = String(minutes % 60);
hours = Math.floor(minutes / 60);
hrs = String(hours % 24);
days = Math.floor(hours / 24);
days = String(days);
timeLeft = days + " days "+hrs+" hours "+mins+" minutes and "+secs+" seconds left";
document.getElementById('countdown').firstChild.data = timeLeft;
setTimeout("timer()",1000);
}
// ]]>
</script>
</head>
<body onload="timer()">
<span id="countdown"> </span>
</body>
</html>
