The code is incorrect in many ways :(.
All functions are called at once, because their time (t) is the same.
if you want to increase t , you probably shouldn't declare it on every acces (use var t = ... only once, after which you can access it by name: t = ... ), and you, probably should use += instead of =+ :
a += b is a shortcut for a = a + b , and a =+ b is a shortcut to a = parseInt(b) .
You probably wanted to write:
var timer = []; var t=0; var step=1000; counter.hide(); t += step; timer[0] = setTimeout("$('#twCharCount').show()", t); t += step; timer[1] = setTimeout("$('#twCharCount').hide()", t); t += step; timer[2] = setTimeout("$('#twCharCount').show()", t); t += step; timer[3] = setTimeout("$('#twCharCount').hide()", t); t += step; timer[4] = setTimeout("$('#twCharCount').show()", t);
One more thing, it's better to pass a function than a string as the first parameter to the setTimeout function:
setTimeout(function(){$('#twCharCount').show();},t);
Sry, but I canβt help myself, this is optimized code for you:
var timer = [], step = 1000, n = 4, el = $('#twChartCount'); for(var i=0;i<n;i++) if(i%2) timer[i] = setTimeout(function(){el.hide();},i*step); else timer[i] = setTimeout(function(){el.show()},i*step);
source share