Reputation: 1305
I want to replace a value in a div
with id show_num_val
with new value for every 5 seconds. For that I have written the following.
<div id="show_num_val"> 0 </div>
In the script:
<script>
$(document).ready(function() {
for(i=0;i<20;i++){
showThis(i);
}
});
function showThis(x) {
setTimeout(function() {
$('#show_num_val').html(x);
}, 5000);
}
</script>
But I am getting the last value i.e 20
only in the show_num_val
div.
can anybody help?
Upvotes: 2
Views: 122
Reputation: 7452
See it working http://jsbin.com/ajekeq/2/watch
<script>
$(document).ready(function() {
for(i=1; i<20; i++){
showThis(i, 5000 * i));
}
});
function showThis(x, y) {
setTimeout(function() {
$('#show_num_val').html(x);
}, y);
}
</script>
The reason why your code was not working because all the timers were getting over at the same time. I would have liked to use setInterval though as we are starting 20 timers at the same time. Another model is to start next timer in the setTimeout call till you are done.
Upvotes: 0
Reputation: 148150
You can use setInterval() if you want repetitive execution.
$(document).ready(function() {
x = 1;
inverval = setInterval(function() {
$('#show_num_val').html(x++);
if(x == 21)
clearInterval(inverval);
}, 2000);
});
Upvotes: 3
Reputation: 87073
var x = 0;
T = setInterval(function() {
if (x == 20) clearInterval(T);
$('#show_num_val').html(x);
x++;
}, 5000);
Upvotes: 3