What is the best way to incrementally add elements and automatically update them in the browser using JavaScript?

Below is a function that triggers when a button is clicked, adding 30 div elements to the document with specific attributes.

var bar_counter = 0;
bar_lengths = new Array();
function createBar(btnObj)
{
    while(bar_lengths.length < 30){
        var size =  Math.floor(Math.random() * (50 - 1) ) + 1;
        
        if(size>50)
        {
            alert("Please enter a value between 1 and 50 only!");
        }
        else{
            if(bar_lengths.indexOf(size) === -1){
                bar = document.createElement("div");
                bar_counter = parseInt(bar_counter) + parseInt(1);
                bar.setAttribute("class","bars");
                bar.setAttribute("name","bar"+bar_counter);
                bar.setAttribute("id",size);
                bar.style.height=10*size+"px";
                var color1 = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
                var color2 = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
                
                bar.style.backgroundImage="linear-gradient(359deg,"+color1+","+color2+")";
                bar.insertAdjacentHTML("beforeend","<font color='red' style='vertical-align: text-bottom; background-color:white'>"+size+"</font>");
                bar.insertAdjacentHTML("beforeend","<font color='red' style='vertical-align: text-bottom; background-color:white'> </font>");
                var place_to_insert = document.getElementById("placeBars");
                place_to_insert.appendChild(bar);
                bar_lengths.push(size);
            }
        }
    }
    btnObj.disabled=true;
    temp="";
    for(var i= 0; i < bar_lengths.length; i++) {
        temp = temp+bar_lengths[i]+" , ";
    }
    document.getElementById("YourArray").innerHTML = temp;
}

While the function works flawlessly, the browser window instantly fills with 30 div elements upon button click. I am looking to introduce a delay in the loop to show each div being added one by one. I attempted using setTimeout() and setInterval() functions without success. Any suggestions would be greatly appreciated. Thanks in advance.

~regards

Answer №1

If you need to introduce a delay in your code, you can make use of this simple helper function:

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

Then, you can simply call await delay(2000) for a 2-second delay.

Remember that the surrounding function must be marked as async to utilize the await keyword.

Answer №2

Implementing a simple method for looping with delay...

const maxLoopCount = 30
  ;
let currentLoopCount = 1
  , intervalReference = setInterval(() =>
      {
        // Add your code here
        // ...

      if (++currentLoopCount > maxLoopCount) clearInterval(intervalReference)
      }
      , 1000); // Set the delay value

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

AngularJS ui-router, html5Mode, and Express causing "Cannot GET" error in nested state

Currently, I am facing an issue while trying to implement $locationProvider.html5Mode(true) with AngularJS, ui-router, and ExpressJS. The problem arises when navigating to a nested state parent.child with URL /child, as refreshing the page or directly typi ...

Acquiring a property from an object that is specified within a function

I have created an object with properties inside a function: function createObject() { const obj = { property1: value, property2: value } } How can I access this object from outside the function? Would redefining it like ...

Breaking down an array in Node.js

After web scraping, I retrieved an array structured like this: array: [ 'line1', 'line2', 'line3', 'linen'.. ] My task now is to insert this data into a MySQL table. The challenge is that every 10 lines of ...

Are you experiencing difficulties with coding text emails?

I am currently in the process of sending an email with an attached PDF file. Here is the code snippet I am using: $mpdf->WriteHTML($html); $content = $mpdf->Output('', 'S'); $content = chunk_split(base64_encode($content)); $ ...

Pedaling back and forth along a sequence

Is there a way to implement forward and backward buttons for a clickable list without using arrays, as the list will be expanding over time? I have already achieved changing color of the listed items to red, but need a solution to navigate through the list ...

Combining one item from an Array Class into a new array using Typescript

I have an array class called DocumentItemSelection with the syntax: new Array<DocumentItemSelection>. My goal is to extract only the documentNumber class member and store it in another Array<string>, while keeping the same order intact. Is th ...

Using preventDefault on an anchor tag with the tel: protocol is ineffective

When a user clicks on a telephone number it should do nothing on desktop and on mobile it should call the number. Finding a solution seemed straightforward by using return false or preventDefault on desktop, but that approach has not proven effective so fa ...

Utilize date-fns to style your dates

Struggling to properly format a date using the date-fns library. The example date I'm trying to work with is 2021-09-20T12:12:36.166584+02:00. What am I doing wrong and what is the correct approach? Here's the code snippet I have so far: import ...

Express.js and gridfs-stream are unable to retrieve the error

Imagine an effortless image download server where Express.js takes the request, fetches an image from MongoDB GridFS, and serves it as a response. Everything works fine when the request is valid and the file exists. The issue arises when it fails to catc ...

Problem with translating a variable into a selector in JQuery

When attempting to make my Jquery code more flexible, I decided to extract the selector and access it through a variable. However, despite creating variables for both selectors, neither of them seem to be functioning properly. I am confident that the issue ...

Is it possible to ensure that a newly created element functions in the same way as an existing element?

I am currently in the process of developing an application that empowers users to generate new items, modify existing items, or delete items by utilizing corresponding icons located adjacent to each item. When it comes to existing items, the action icon d ...

What is the method for aligning a glyph vertically?

Can anyone help with aligning the glyph vertically to the text? Currently, it seems more like it's attached to the bottom. Here is an example: <a href="#">Zoom</a> a { font-family: 'Open Sans', sans-serif; font-weight: ...

Align the center of a grid div that does not contain any items

Below are the code snippets provided: .grades_dashboard_m {} .three_separation { width: 100%; display: grid; grid-template-columns: 1fr 1fr 1fr; grid-gap: 60px; } .grades_dashboard_box { height: 130px; width: 160px; background-color: #00 ...

Trouble arises when trying to define the style for an element generated through the Document

I'm having trouble setting the style for a 'tr' element created using DOM within JavaScript. Here's the code snippet: var tr = document.createElement("tr"); tr.onmouseover=function(){this.style.backgroundColor='#fbf9e0';}; ...

Access to an Express route in Node JS can only be granted upon clicking a button

Is it feasible to create an express route that can only be accessed once a button is clicked? I want to prevent users from entering the route directly in the URL bar, and instead require them to click a specific button first. I'm curious if this can b ...

How can I detect a DOM element mutation based on a CSS selector, and if this is possible, how can it be accomplished?

Imagine there's a website with a specific HTML element. It seems that this element has the same class during the DOMContentLoaded event as it does during the load event. However, after the load event, this class (and possibly the ID and other HTML att ...

Tips for utilizing ng-repeat with standard JSON data structures

I have a JSON structure like this: [{ Entry: [{ ID:123, Name: 'XYZ', Address: '600, PA' }, { ID:123, Name: 'ABC', Address: '700, PA' }, { ID:321, Name: 'RRR', ...

Tips for creating an HTML report using Python

Currently, I am searching for a solution to convert my saved matplotlib graphs as png files along with some data frames into HTML format. This is similar to how I typically use R2HTML in R. Despite my efforts, I have not been able to locate clear informat ...

"Using Flexbox to Align Child Elements of Varying

After learning about flexbox, a pressing question arose: How can I create a layout of columns similar to the one shown in this image? Check out MyCodeFiddle for more details! (http://jsfiddle.net/1s3bo913/) Click here to view the layout project: Layout Pr ...

Price Adjuster Tracker

Recently, I coded a small JavaScript program with the purpose of: incrementing or decrementing the quantity of an item by 1 adjusting the price of an item based on the initial price However, my excitement turned to disappointment when I encountered these ...