Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create DOM elements by a limited interval with Jquery [duplicate]

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?

like image 414
peterHasemann Avatar asked Jan 26 '26 15:01

peterHasemann


2 Answers

Replace var with let.

for (let i = 0; i < 5; i++) {

Demo

$(document).ready(function() {
  for (let 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>

Reason

var doesn't let go of the bindings of the parent lexical-environment hence its hoisted value is retained in the asynchronous callback handler (of setTimeout), however let doesn't hold on to the bindings of any lexical-environment other than its own current one.

like image 152
gurvinder372 Avatar answered Jan 29 '26 03:01

gurvinder372


please update your code. no need of for loop.

var i=1;
$(document).ready(function() {

  setInterval(function() {
      createEle(i);
    }, i * 1000);
});

function createEle(value) {
  var d = $("<div></div>");
  d.addClass("d");
  d.html(value);
  $("#container").append(d);
  i++;
}
like image 40
Negi Rox Avatar answered Jan 29 '26 05:01

Negi Rox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!