闪烁文本和闭包

时间:2012-03-13 01:20:25

标签: javascript closures

我希望页面上的一些文字每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 个答案:

答案 0 :(得分: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. 我们不会每2秒为您的元素查询一次DOM。我们缓存它一次,然后重复使用它。
  2. 每次都不需要创建新的颜色数组。
  3. 最后,我们将整个事情包装在一个自动执行的匿名函数中,这样我们就不会用这些变量污染全局命名空间。
相关问题