2012-03-13 38 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;} 

的問題是,當我看到Chrome的時間表,我看到內存使用量上升,每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); 

您可以進一步優化該代碼如下:

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 2012-03-13 12:45:05