I’m looking to make some text on the page change colors every 2 seconds. This is what I have:
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);
}
And then for the css I have this:
#TheText{
-webkit-transition:all 2s ease;
-moz-transition:all 2s ease;
-o-transition:all 2s ease;
transition:all 2s ease;}
The problem is that when I look at the timeline in chrome, I see the memory usage go up and up every 2 seconds. I suspect the reason memory usage continuously expands is that there’s a memory leak and that I’m creating an accidental closure.
What’s wrong with my code?
Thanks for your suggestions.
You are calling
setTimeoutfrom within your function, thus adding to the stack with each call.Instead, use an interval call from outside the function:
You can further optimize this code as follows:
We’re doing 3 things differently here: