javascript using settimeout() with a loop

后端 未结 4 1612
醉酒成梦
醉酒成梦 2021-01-24 20:21

ive got a table with 8x10 cells.. each sell got an input element with its own id (11, 12, ... , 21,22,23,...) now i want to fill these inputs after and after (lets say 0.5 sec)

相关标签:
4条回答
  • 2021-01-24 20:43

    You can try something like this:

        var i = 1;
        var k = 1;
        var obj = setInterval( function () {
            document.getElementById(i + '' + k).value= Betrag[i][k];
            if(k <= 10)
               k++;
            else
            {
                k = 1;
                if(i<=8)
                     i++;
                else
                     clearInterval(obj);
            }
        }, 1000);
    

    Here's a running example at http://jsfiddle.net/Ex98V/

    0 讨论(0)
  • 2021-01-24 20:55

    k and i are read after the for loop ended (1 second to be precise). Their values are then 9 and 11, leading to an array overflow problem.

    One option to fix it, is to create a function that does the work, and create a fixed string from the k and i variables to call it:

    function schreiben(__i, __k) {
       document.getElementById(''+__i+__k+'').value= Betrag[__i][__k];
    }
    

    Then call the setTimeout like this:

    setTimeout("schreiben("+i+","+k+")", 1000);
    

    Not the most elegant way, but it works.

    0 讨论(0)
  • 2021-01-24 20:58

    This should work the way you wanted.

    for(i=1; i<=8; i++){
        for(k=1; k<=10; k++){
            (function(i, k){
                setTimeout(function schreiben(){document.getElementById(''+i+k+'').value= Betrag[i][k];}, 1000*k + 10000*i);
                //document.getElementById(''+i+k+'').value= Betrag[i][k];
            })(i, k);
        }
    }
    

    To make things a bit clearer, consider refactoring like this :

    for(i=1; i<=8; i++){
        for(k=1; k<=10; k++){
            setSchreibTimeout(i, k);
        }
    }
    
    function setSchreibTimeout(i, k){
        setTimeout(function schreiben(){document.getElementById(''+i+k+'').value= Betrag[i][k];}, 1000*k + 10000*i);
        //document.getElementById(''+i+k+'').value= Betrag[i][k];
    }
    
    0 讨论(0)
  • 2021-01-24 21:03

    Bart Friederichs is right. Not sure why you want to do this that way, but you can declare a couple of vars inside the schreiben function and increment them inside the same screiben function.

    0 讨论(0)
提交回复
热议问题