Forum Moderators: open
"Warning: assignment to undeclared variable timeoutID
Source File: file:///c:/htmlplay2/pro1LeadImage/whyIwasLookingFor.htm
Line: 15"
Also this error message.
"Error: MyFunc is not defined
Source File: file:///c:/htmlplay2/pro1LeadImage/whyIwasLookingFor.htm
Line: 15"
I would appreciate it very much if somebody could help me get this code going. Below is all that I have mentioned above.
" Many designs using a for or while loop structure may instead have needed the setTimeout() method of the window object calling a function recursively. The general form of this structure is:
<!--
function MyFunc() {
//code here
timeoutID = setTimeout("MyFunc()", 1000)
}
-->
where timeoutID is a script-global variable. After MyFunc() is called, this structure then recursively calls MyFunc() every second until clearTimeout(timeoutID) is used. Unlike a for or while loop, this "loop" is time based."
My code.
<!--
<head>
<title></title>
<script language="JavaScript">
<!--
var c=0;
var timeoutID=0;
function MyFunc() {
c += 1;
window.document.write(c + "</br>");
timeoutID = setTimeout("MyFunc()", 1000);
}
-->
</script>
</head>
<body onload="MyFunc()">
</body>
</html>
-->
In fact this is a slightly convoluted issue, because the delayed command itself isn't wiped out. Let's just leave this as "avoid document.write" for now.
Here's a variation for you.
Note that the value a timeout returns only needs to be saved if you want to cancel it.
<html><head>
<script type="text/javascript">
var c=0;
var timeoutID;
function MyFunc()
{
document.getElementById('counter').innerHTML = ++c;
timeoutID = setTimeout("MyFunc()", 1000);
}
</script>
</head>
<body onload="MyFunc()">
<h1 id="counter">0</h1>
<input type="button" value="stop" onclick="clearTimeout(timeoutID)">
</body>
</html>