Javascript 闪烁文本和闭包
我想让页面上的一些文字每2秒改变一次颜色。这就是我所拥有的: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('
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);
我们在这里做了三件不同的事情: