Generating DOM elements at specific intervals using Jquery

I am looking to dynamically create 1 div container every x seconds, and repeat this process n times.

To achieve this, I have started with the following code:

$(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>

The current implementation is functional, but I would like to incorporate a time interval feature.

$(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>

In the second example provided, I encountered an issue where the wrong index value was being passed. How can I rectify this?

Answer №1

Switch var to let.

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

Example

$(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>

Explanation

var does not release the bindings of the parent lexical environment, which is why its hoisted value remains in the asynchronous callback handler (of setTimeout). On the other hand, let does not hold onto the bindings of any lexical environment other than its own current one.

Answer №2

Kindly make improvements to your script without utilizing a for loop.

let num=1;
$(document).ready(function() {

  setInterval(function() {
      generateElement(num);
    }, num * 1000);
});

function generateElement(value) {
  let div = $("<div></div>");
  div.addClass("d");
  div.html(value);
  $("#container").append(div);
  num++;
}

Answer №3

Before the first setTimeout is triggered, the loop will complete its execution. Therefore, the value of i will be 5.

It is important to treat setTimeout and setInterval as asynchronous functions.

$(document).ready(function() {
  var i = 0;
  var tmer = setInterval(function() {
    createEle(i);
    i = i + 1;
    if(i==5)
      clearInterval(tmer);
  }, 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding your way through Bootstrap Datepicker using the Previous and Next Buttons

Is there a way to implement Previous and Next Button functionality for navigating a Bootstrap Datepicker using jQuery, similar to the illustration below? https://i.sstatic.net/e9I7P.png I attempted the following approach: function PrevNext(isnextbtn) ...

Problem with Material-UI Drawer

Is there a way to make this drawer stay fixed on the page like a sticker and remain active without moving when scrolling? I've tried using docked={false}, but it makes the whole page inactive except for the drawer. Any suggestions on how to solve this ...

Experience a dynamic search feature seamlessly integrated within the jqGrid interface

I tried implementing the integrated Search toolbar from jqgrid demos, but I'm facing an issue. Unlike the demo where search is triggered as soon as a character is entered, in my case I have to press enter for it to initiate the search. Can anyone poin ...

Tips for enhancing a JSON array by including attributes through JavaScripts

I need help in dynamically constructing JSON using Javascript. { "Events": [{ "Name": "Code Change", "Enabled": "true", "Properties": [{ "Name": "url", "Value": "val" }] }], "Properti ...

Converting HTML to PDF: Transform your web content into

I have a couple of tasks that need to be completed: Firstly, I need to create a functionality where clicking a button will convert an HTML5 page into a .PDF file. Secondly, I am looking to generate another page with a table (Grid) containing data. The gr ...

What could be the reason for the excess white space at the top and bottom of the page?

Once I implemented a new div class to incorporate a background image, the top, bottom, and side menus on my page suddenly turned white. style.css #boundless{ background-image:url('http://thehypebr.com/wp-content/uploads/2010/09/boundless-sem-branc ...

What is the best approach for managing caching effectively?

My SPA application is built using Websocket, Polymer, ES6, and HTML5. It is hosted on a Jetty 9 backend bundled as a runnable JAR with all resources inside. I want to implement a feature where upon deploying a new version of the JAR, I can send a message ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

Combining strings in a loop using Javascript

I have a loop hash data stored in a variable called rec. var rec = { }; for (var b = 0; b < 2; b++) { rec['id'+b] = b</p> } Next, I have a piece of JavaScript code that creates a template for a table. var template ='<tab ...

Adjust the placement of a div within another div based on various screen sizes dynamically

Currently, I am working on an Ionic 2 app where the user is required to select specific points on the screen. These coordinates will then be utilized on another screen with a different size. My initial attempt at using rule of three/cross multiplication pr ...

The process of organizing and arranging the content that appears on a webpage is in

Seeking a solution to achieve a similar effect like this example. Wanting the sections to transition nicely when clicked on. Should I use a Jquery plugin or implement it with CSS? ...

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...

The function initFoodModel is missing and causing issues as it tries to read properties of undefined, specifically attempting to read 'findAll'

myWishlist.js const { setupFoodModel } = require("../../model/FoodModel"); const { setupWishlistModel } = require("../../model/myWishlistModel"); const setupMyWishlistModel = async () =\> { try { const sequelizeConnection = awai ...

Creating a CSS3 web design inspired by the Facebook-image style - here's how!

Looking to create a design using CSS that mimics the facebook-image-container, similar to this example: . Seeking advice on how to achieve this effect. The concept is to have a centered box on the page, with one half displaying an image and the other conta ...

When scraping daily HTML tables with Selenium, I am only able to retrieve the last page

Exploring web scraping to gather data for my latest project has been quite the adventure. This is my first attempt at extracting information from websites, specifically prices that are listed on a website. The challenge I am facing is that I require this d ...

Adjusting the Height of the Video Jumbotron in Bootstrap

One of my main goals is to create a jumbotron with a video that plays, occupying 100% width and 70% height of the screen. However, I am facing an issue where the video follows the scrolling behavior when I don't want it to. Specifically, as I scroll d ...

Obtaining output values from a POST request

When making a GET request through Ajax using jQuery, the URL displayed in the Chrome console is script.php?param=1. $.ajax({ type : "POST", url : "script.php", data : { q : "save", query : query // a variable }, succe ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

Rotating Image Carousel

Attempting to implement a Carousel Slider similar to the following example: <section> <div><br> <div class="arrows"> <div class="seta-x"> <a href="#" class="arrow-left"></a> ...

Adjust Javascript to modify the URL by assigning a new URL without utilizing the origin as the parent

Currently, I am working on a script that is responsible for sending string values to the server in order to change the ipv4 information on a specific device. However, I am facing some difficulties and would appreciate some assistance with automatically upd ...