Search code examples
javascriptjqueryloopssetintervalqueuing

Chaining similar elements modification by time interval


I have a given list of p elements on my html code. On page load, I try to queuing modifications of each <p> elements's content by a given interval of time (1sec).

Given the html:

<p>I want to change first!</p>
<p>I want too!</p>
<p>Me 3rd !</p>
<p>Hey, don't forget me!</p>

the CSS:

p { padding: 2px 5px 0px 10px; }
.p { color: #999; }
.green { color:green; border-bottom: 1px solid #888; background: #EEE; }

What should be the JS to since I want to chain up modification. Literally: the first p sentence to be CSS / HTML modified first, 1sec later the 2nd line should be replaced, 1sec later the 3rd line, 4sec later the 4th line, etc.

$("p").ready(function(){
    setInterval(function () {
        $('p').text('aaaahhhhh.... happy!')
    }, 1000);
  });

That's fail (fiddle).

What I am doing wrong ? should I use a for loop, each(), instead of selector + setInterval ? please forward keywords so I may dig in the relevant docs. Fiddle appreciate~


Solution

  •     function modifyTargetDeferred(target) {
            target.first().text('ahhh... happy');
            if (target.length > 1) {
                setTimeout(function() {
                    modifyTargetDeferred(target.not(':first'));
                }, 1000);
            }
        }
    
        setTimeout(function() {
            modifyTargetDeferred($('p'));
        }, 1000);