jQuery update element using .each() [closed]
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);
},开发者_JAVA百科 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/
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);
精彩评论