Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 闪烁文本和闭包_Javascript_Closures - Fatal编程技术网

Javascript 闪烁文本和闭包

Javascript 闪烁文本和闭包,javascript,closures,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('

我想让页面上的一些文字每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秒就不断上升。我怀疑内存使用量持续增加的原因是内存泄漏,我正在创建一个意外关闭

我的代码怎么了


谢谢您的建议。

您正在从函数中调用
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);
我们在这里做了三件不同的事情:

  • 我们不会每隔2秒查询DOM中的元素。我们缓存它一次,然后重用它
  • 也不需要每次都创建一个新的颜色数组
  • 最后,我们将整个过程包装在一个自动执行的匿名函数中,这样我们就不会用这些变量污染全局名称空间