I want to create 1 div container every x
second. And I want to do this n
times.
So I started creating this
$(document).ready(function() {
for (var i = 0; i < 5; i++) {
createEle(i);
}
});
function createEle(value) {
var d = $("<div></div>");
d.addClass("d");
d.html(value);
$("#container").append(d);
}
.d {
height: 20px;
color: white;
background: red;
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
this works fine. But I want to integrate the time interval.
$(document).ready(function() {
for (var i = 0; i < 5; i++) {
setTimeout(function() {
createEle(i);
}, i * 1000);
}
});
function createEle(value) {
var d = $("<div></div>");
d.addClass("d");
d.html(value);
$("#container").append(d);
}
.d {
height: 20px;
color: white;
background: red;
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
As you can see in the second example, I always get the wrong value because it passes in the wrong index value.
How can I fix that?