views:

90

answers:

1

HTML code:

div id="updatePanel">​

jQuery code:

var data=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

$.each(data, function(index, value) {
  setTimeout(function(){ 
     $('#updatePanel').text(index);     
  }, 5000 ); 
}); 

I want the updatePanel div content to be updated every 5 seconds. It should be 1 then wait 5 seconds, display 2, wait for another 5 seconds......

It doesn't work like what i expected. It waits for 5 seconds and display 9.

See the demo here: http://jsfiddle.net/vc7qB/4/

+8  A: 

Change the }, 5000 ); to }, 5000*index );

This will make each item to wait 5 seconds more than the previous ...

Keep in mind that all the timeouts get created at the same time, but with different delay times..

It would be better to start with a single timeout and at each execution create the next one ..

like this

var data=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    function update(idx){
        setTimeout(function(){
        $('#updatePanel').text( data[idx] );
        if (idx < data.length - 1)
            update(idx+1);
        },1000);
    }

update(0);
Gaby
+1 concise, clever!
naikus
"Keep in mind that all the timeouts get created at the same time..." I don't fully understand this part. I thought .each is basically the same as for loop. The following code:$.each(data, function(index, value) { $('#updatePanel').html(index);}); should loop though each element and update the updatePanel sequentially. This $.each(data, function(index, value) { setTimeout(function(){ $('#updatePanel').text(index); }, 5000 ); }); should set the timeout every 5 seconds. Can you explain why the timeouts get created at the same time? Thanks.
@user187870, just as in a loop, your timeouts all get created within millisecond from each other. They all wait 5 seconds, so they all expire almost at the same time, so the update happens for all of them and the last one is what you see in your div.. in my example we multiple the delay of each with their index in the array, so the first will wait 5000x1, the second 5000x2 etc.. (*effectively every 5 seconds*)
Gaby