2011-06-18 10 views
0

私はちょっとした "Matrix"テーマプログラムを作ろうと思っています。ユーザーに名前を入力させてから、彼らの名前の1秒ごとに、左から右。私は間違って何をしていますか?これまでの作業は数字のスクロールです他のコンテンツの前にJavaScriptを使ってコンテンツを追加する

<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> 

答えて

2

setIntervalはループです。追加のforループは必要ありません。また、set intervalの戻り値を格納するように変数を設定して、後で実行を停止したいときにクリアすることができます。ここ

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); 

} 

フィドル(デモ):http://jsfiddle.net/jW8hZ/

+0

はそんなにありがとう:)私は私の髪を引っ張りました! – bruchowski

+0

心配する必要はありません。 –

0

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); 

} 
関連する問題