I've tried finding my answers in other posts and can find bits and pieces, but not a complete answer. So, sorry if this is a duplicate question - best I can tell, it's not.
I'm trying to accomplish three things:
- Delay iterating through a for loop for one second between itmes
- Revert the previous item to its original state before moving on to the next item
- Start the loop all over again after the last item
I've accomplished the first, but can't figure how to accomplish the next two.
Here's a watered-down code sample:
HTML:
<p>First paragraph.</p>
<p>Second paragraph.</p>
<p>Third paragraph.</p>
<p>Fourth paragraph.</p>
<p>Fifth paragraph.</p>
<p>Sixth paragraph.</p>
<p>Seventh paragraph.</p>
<p>Eighth paragraph.</p>
<p>Nineth paragraph.</p>
<p>Tenth paragraph.</p>
CSS:
p.red {color: red;}
JS:
function addRed() {
var spans = $('p'),
count = spans.length,
delay = 1000;
for(var i = 0; i <= count; i++) {
(timer(i, spans, delay));
}
}
function timer(a, b, c) {
setTimeout(function() {
$(b[a]).toggleClass('red');
}, c * a);
} (0);
addRed();
I'd like for the first <p> in this example to turn red, wait for one second, then turn the second <p> red and revert the first back to its original state. Then, once the cycle has completed (iterated through the entire list of <p>s), start again at the top. I.e.; a repeating loop.
Sorry if this is asking three separate questions. It's easier and makes more sense to just group them all together.
Here's my fiddle.
As a final note, I'm not tied to any of this code. If needed, I'm open to changing it.