0

So what I'm trying to accomplish now is actually just a simplified version of a small project I'm working on. What I'm trying to do first is to have a table of 10 rows with each row having one value in it. After 5 seconds, the function makeTable will run and increment the values in each cell. Right now, all I end up with is an endless loop where it is constantly incrementing the values if I put an alert/document.write check after the inner HTML is changed.

Ultimately, I want to replace the numbers with images, but if I can at least get the numbers working, then I can build on top of that. Any help you guys can give would be great. Thank you!

    <html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>

<script type="text/javascript">

document.write("<table>");  
    var i;
    for(i=0;i<10;i++){

        document.write('<tr><td id="Cell' + i + '">'+i+'</td></tr>\n');
    }
    document.write("</table>");


function makeTable(n){
    for(i=n;i<10+n;i++){
        var cell="Cell"+i;  
        document.getElementById(cell).InnerHTML=i+1;

    }   
setTimeout(makeTable(n+1), 5000);
}

setTimeout(makeTable(1), 5000);

</script>
</head>

<body>
</body>
</html>
gdawgrancid
  • 640
  • 3
  • 15
  • 37

2 Answers2

1

1.) wrap calling makeTable(...) in a function:

setTimeout(function() { makeTable(...); }, 5000);

2.) Remove the n from the for-loop:

for(i=0;i<10;i++) {

3.) InnerHTML has to be innerHTML and add with n:

document.getElementById(cell).innerHTML=i+n;

Also see this example (in the example the setTimeout(...) will be caled until n is less 5).

Update: here the changed code:

function makeTable(n){
    for(i=0;i<10;i++){
        var cell="Cell"+i;  
        document.getElementById(cell).innerHTML=i+n;
    }   
    setTimeout(function() { makeTable(n+1); }, 5000);
}

setTimeout(function() { makeTable(1); }, 5000);
scessor
  • 15,995
  • 4
  • 43
  • 54
1

This code should work for you, edit: without evil:

<html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>

</head>

<body>
<script type="text/javascript">
var n = 0;

document.write("<table>");
var i;
for(i=0;i<10;i++){
    document.write('<tr><td id="Cell' + i + '">'+i+'</td></tr>\n');
}
document.write("</table>");



function makeTable(){
    n++;
    for(i=0;i<10;i++){
        var cell="Cell"+i;
        document.getElementById(cell).innerHTML=n + i;
    }

    timer();
}


function timer(){
    setTimeout(makeTable,5000);
}

timer();

</script>

</body>
</html>
Stig Hausberg
  • 836
  • 6
  • 9
  • If the first parameter in `setTimeout()` is a string, `eval()` will be used (again) (see [this link](https://developer.mozilla.org/en/DOM/window.setTimeout#Passing_string_literals))! – scessor Feb 03 '12 at 08:20
  • It would be better to use `t = setTimeout(makeTable, 5000);`. – scessor Feb 03 '12 at 08:31