...

View Full Version : problem with setTimeout()



mat106
12-11-2004, 02:11 AM
Hello.

Can anyone see why this simple script will not loop as it's supposed to?



<html>
<head>
<script>
function depart() {
today = new Date();
leave = new Date(2004, 12, 18, 13, 30, 00, 0);
difference = leave.getTime() - today.getTime();
document.write ("<h1>" + difference + "</h1>");

setTimeout ("depart()", 1000);
}
</script>
</head>
<body onload="depart();">
</body>
</html>


The debugger in firefox says "depart is not defined"

glenngv
12-11-2004, 07:55 AM
Because when you document.write after the page has loaded, the current page will be overwritten by the new string. So the next time depart() is called, it is not there anymore because the page is already replaced. Use innerHTML or DOM to display the string without replacing the whole page.


<html>
<head>
<script>
function depart() {
var today = new Date();
var leave = new Date(2004, 12, 18, 13, 30, 00, 0);
var difference = leave.getTime() - today.getTime();
document.getElementById("diff").innerHTML = difference;
setTimeout ("depart()", 1000);
}
</script>
</head>
<body onload="depart();">
<h1 id="diff"></h1>
</body>
</html>

mat106
12-11-2004, 10:55 AM
That's great - A clear explanation and a solution to the problem. Thanks glenngv :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum