开发者

Adding content using Javascript before other content

So I'm trying to make a 开发者_JS百科little "Matrix" themed program, I want the user to input their name, and then the program will run through 20 numbers every second as it displays each character of their name every 1 second, from left to right. What am I doing wrong? All that's working so far is the number scrolling

<html>
<head>
    <script type="text/javascript">
    var name = prompt("Enter Your Name to be 'MatrixIzed!':", "");

    function numberScroll(){
        for (i=0;i<name.length;i++){

            setInterval(function() {
                    var n = Math.floor(Math.random() * 9);
                    document.getElementById('txt2').innerHTML = n;
                }, 50);

            setInterval(function() {
                    document.getElementById('txt1').innerHTML = name.charAt(i);
                },1000);
        }
    }
    </script>
</head>
<body onLoad="numberScroll()">
    <div style="float:left" id="txt1"></div>
    <div id="txt2"></div>
</body>
</html>


The setInterval is the loop, you don't need additional for loop. Also, you should set variable to store return value from set interval so you can clear it later when you want it to stop running.

function numberScroll(){

    // no need to loop i, just set it and increment it in the interval
    var i = 0;

    // store interval as variable, so you can stop it later
    var numbers = setInterval(function(){
        var n = Math.floor(Math.random() * 9);
        document.getElementById('txt2').innerHTML = n;
    }, 50);

    var letters = setInterval(function(){
        // `+=` rather than `=` to incrementally add to the div's inner html
        // use and increment i in one step with `i++`
        document.getElementById('txt1').innerHTML += name.charAt(i++);
        // when it has reached the end of the name, clear the intervals and empty the second div
        if(i >= name.length){
            clearInterval(numbers);
            clearInterval(letters);
            document.getElementById('txt2').innerHTML = '';
        }
    },500); 

}

Fiddle (demo) here: http://jsfiddle.net/jW8hZ/


you need to iterate through all the letters inside the setInterval.

function numberScroll(){
   setInterval(function() {
     var n = Math.floor(Math.random() * 9);
     document.getElementById('txt2').innerHTML = n;}
     , 50);


   var i=0;
   setInterval(function() {
     document.getElementById('txt1').innerHTML = name.charAt(i);
     i = (i+1)%name.lenghth;
     }
     ,1000);

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜