programforjoy programforjoy - 2 years ago 122
Javascript Question

javascript: using settimeout in a for loop to show text at regular intervals

I want to show 3 lines at regular intervals(one second),here's the code:

<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
function showText()
var itemlist = document.getElementsByClassName("test");
function additem(index) {
setTimeout(function(){itemlist[index].setAttribute("style", "display:block;");}, 1000);
for(var i=0;i<itemlist.length;++i) {

<input type="button" value="show" onClick="showText()">
<div class="test" style="display:none">first</div>
<div class="test" style="display:none">second</div>
<div class="test" style="display:none">third</div>

But the result is: when I click the show button,a second later,
all three div block appear together.I was expecting they will be displayed one by one with an interval of one second.

How can I fix this? Hope for your help.

Answer Source

You're calling all of them at the same time. Using just line1 for clarity.

setTimeout(line1, 1000);
setTimeout(line2, 1000);
setTimeout(line3, 1000);

They don't "stack". All three functions will run in 1 second.

You have two options. Option 1:

setTimeout(line1, (1 + index) * 1000);
setTimeout(line2, (1 + index) * 1000);
setTimeout(line3, (1 + index) * 1000);

This will cause them to timeout one after another.

The other option is making the timeout call the next one:

var index = 0;
function showNextLine() {
    // show line index
    if (index < 3) {
       setTimeout(showNextLine, 1000);
setTimeout(showNextLine, 1000);

This way they "chain" like you might be expecting.

There are other variations, and you could even use setInterval() and clearInterval().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download