2012-03-13 16 views
0

2秒ごとにページのテキストの色を変えたいと思っています。これは私が持っているものです。点滅するテキストとクロージャ

function BlinkText() { 

    var TheTextColors = ['red', 'white', 'blue']; 
    var TheColor = Math.floor(Math.random() * 3) + 1; 

    var TheOpacity = (Math.floor(Math.random() * 20) + 80)/100; 

    $('#TheText').css('color', TheTextColors [TheColor]); 
    $('#TheText').css('opacity', TheOpacity); 

    setTimeout(BlinkText, 2000); 
} 

そしてCSSの私はこれを持っている:

#TheText{ 
    -webkit-transition:all 2s ease; 
    -moz-transition:all 2s ease; 
    -o-transition:all 2s ease; 
    transition:all 2s ease;} 

問題は、私はクロームでタイムラインを見たとき、私はメモリ使用量が上がると見ていることです2秒ごとに起動します。私は、メモリの使用が継続的に拡大する理由は、メモリリークがあり、私が偶発的な閉鎖を引き起こしているということが原因だと思われます。

私のコードで何が問題になっていますか?

ご意見ありがとうございます。

答えて

1

関数内からsetTimeoutを呼び出すと、呼び出しごとにスタックに追加されます。次のように

function BlinkText() { 

    var TheTextColors = ['red', 'white', 'blue']; 
    var TheColor = Math.floor(Math.random() * 3) + 1; 

    var TheOpacity = (Math.floor(Math.random() * 20) + 80)/100; 

    $('#TheText').css('color', TheTextColors [TheColor]); 
    $('#TheText').css('opacity', TheOpacity); 
} 

setInterval(BlinkText, 2000); 

あなたはさらに、このコードを最適化できます::私たちは異なり、ここで3つの事をやっている

var BlinkText = (function() { 

    var TheTextColors = ['red', 'white', 'blue'], 
     $element = $('#TheText'); 

    return function() 
    { 
     var TheColor = Math.floor(Math.random() * 3) + 1, 
      TheOpacity = (Math.floor(Math.random() * 20) + 80)/100; 

     $element.css({ 
      'color': TheTextColors[TheColor], 
      'opacity': TheOpacity 
     }); 
    }; 
}()); 

setInterval(BlinkText, 2000); 

代わりに、機能外部からの間隔の呼び出しを使用します。

  1. DOMを照会していませんあなたの要素の2秒ごとに。一度キャッシュして再利用します。
  2. 毎回新しい色の配列を作成する必要はありません。
  3. 最後に、グローバルな名前空間をこれらの変数で汚染しないように、すべてを自己実行型の匿名関数にラップします。
+0

あなたのご意見ありがとうございます。本当に役に立つパターン。 – frenchie