Integrate individual characters into the div element sequentially using javascript, rather than all at once

After a few years, I decided to dive back into experimenting with JavaScript. I've encountered a situation where I'm trying to add the character "X" to a div element one at a time, instead of all at once. Currently, the DOM seems to be adding them in clusters, leaving my page blank and then suddenly displaying everything together. My goal is to have the "X's" show up individually with a delay of 2 seconds between each addition.

<div id="here"></div>

<script>

function wait(ms) {
    var d = new Date();
    var d2 = null;

    do {
        d2 = new Date();
    }
    while (d2 - d < ms);
}

function runTest() {
    var cnt = 0;

    while (cnt < 50) {
        var x = document.getElementById("here");
        x.innerHTML += "X + ";
        wait(2000);
        cnt++;
    }
}

</script>

Answer №1

It seems that the function wait() is not functioning as expected. The current implementation consists of a loop that consumes resources for a specified duration. To illustrate this issue, consider the following example where two logs are displayed (one before and one after wait()), but only when the function stops consuming resources:

function wait(ms)
{
    var d = new Date();
    var d2 = null;

    do {
        d2 = new Date();
    }
    while (d2 - d < ms);
}

console.log("Before wait() is called");
wait(5000);
console.log("After wait() is done");
.as-console {background-color:black !important; color:lime;}

If you are looking for a more efficient approach, consider using setInterval().

Example with setInterval():

var cnt = 0;
var x = document.getElementById("here");
var ival = setInterval(addX, 2000);

function addX()
{
    if (++cnt > 10)
    {
        clearInterval(ival);
        console.log("Finished!");
        return;
    }

    x.innerHTML += "X + ";
}
.as-console {background-color:black !important; color:lime;}
<div id="here"></div>

To stop the repeated action, utilize clearInterval().

Alternatively, you can achieve your goal by combining a Promise() with setTimeout() to create a modified version of your wait() method. See the example below:

Example with Promise:

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

async function runTest()
{
    var cnt = 0;

    while (cnt < 10)
    {
       var x = document.getElementById("here");
       x.innerHTML += "X + ";
       await wait(2000);
       cnt++;
    }
}

runTest();
<div id="here"></div>

Answer №2

To improve performance, it's recommended to utilize setInterval() instead of wait in JavaScript. Due to the non-threaded nature of Javascript, using wait will halt the entire execution each time it is encountered. The usage of wait() is typically rare and setting an interval to run every X seconds is usually more appropriate.

For example, the code below demonstrates a function that runs every 2 seconds. When the count reaches 50, a message is sent to the DOM instructing the function to stop running.

function divBunches() {
  var elem = document.getElementById("here"); 
  var id = setInterval(addDiv, 2000);
  var count = 0;
  function addDiv() {
    if (count == 50) {
      clearInterval(id);
    } else {
      elem.innerHTML += "X + ";
    }
    count++;
  }
}

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

Updating NavBar text dynamically based on user login status in React.JS

Within my project, there is a Navigation bar that I access from App.js. Depending on whether I am logged in or not, I want to display different versions of the NavBar. When logged in, the NavBar should have a logout button. And when logged out, it should s ...

What is the process for accessing browser API calls through Protractor?

Is there a method to identify if the necessary API has been activated by the browser? Can Protractor provide a list of APIs that have been called? ...

Leveraging several useState hooks

When working on a React Native project, I have implemented multiple hooks to retrieve input data in a form. Are there any alternative methods that are more efficient or better suited for this task? Thank you const [name, setName] = useState(''); ...

The AJAX load event listener triggers prior to receiving a response from the server

When working on a script to upload images via AJAX, the process is as follows: a user selects an image using a form file input field. The form contains an onsubmit function that prevents the page from reloading after submission. Within this function, data ...

Customizing Material UI tooltip styles with inline CSS formatting

Currently in the process of creating a React component that utilizes the Material UI Tooltip feature. In my component, I have the need to manually reposition the Mui Tooltip by targeting the root popper element (MuiTooltip-popper). However, the Mui Toolti ...

Include a predetermined parameter for the upcoming callback

Currently, I am working on loading files asynchronously by utilizing d3's queue, defer, and await features. The issue arises when I attempt to execute this process in a loop, where for each iteration, I aim to store the retrieved data in a dictionary: ...

Access the properties of a JSON object without specifying a key

I am dealing with a collection of JSON arrays structured like this: [ { team: 111, enemyId: 123123, enemyTeam: '', winnerId: 7969, won: 1, result: '', dat ...

Render multiple checkboxes with values from an array of objects passed as a prop to a child component using a v

I am facing an issue with my Vue components 'Parent' and 'Child'. Each child component has a checkbox with a :checked prop. In the Parent component, I iterate through an array of objects and pass props to the child. Although I can emit ...

Struggling with developing a straightforward application with Angular-Material

My goal is to develop an application that utilizes the Angular Material navigation bar, as showcased in this example. Being relatively new to AngularJS, I'm facing an issue where my app loads but only displays a blank page. Below is the code snippet ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

What is the best way to extract and retrieve the most recent data from an XmlHttpRequest?

Currently, I am using a web service that returns an SseEmitter to program a loading bar. The method to receive it looks like this: static async synchronize(component: Vue) { let xhr = new XMLHttpRequest(); xhr.open('PATCH', 'myUrl.co ...

Encountering an issue with React Router v6 where calling `history.push('/')` results in an error of "undefined (reading 'pathname')" - the URL changes, but the page remains unchanged

Having an issue altering the page within a Redux Thunk action creator to redirect the user back to the homepage after form submission Although the URL changes when the action creator is triggered, the page itself remains the same Unable to utilize Browse ...

Update dynamically generated CSS automatically

Is there a way to dynamically change the CSS? The problem I'm facing is that the CSS is generated by the framework itself, making it impossible for me to declare or modify it. Here's the scenario at runtime: https://i.sstatic.net/IovGr.png I a ...

Sending files to an FTP server using Vue.js

Currently, I am developing a data analysis web application that enables users to upload files to an FTP server and access results after performing calculations. My current challenge lies in creating a user-friendly interface for file uploads. The main que ...

What should I do to resolve the error message TypeError: _components_firebase_Firebase__WEBPACK_IMPORTED_MODULE_2__.default.auth is not a valid function?

I have implemented Firebase with next.js and organized my files as shown below. However, I am encountering an issue with using the firebase client side SDK during the sign-up process. Firebase.js is where the firebase app is initialized import firebase fr ...

Incorporating External JavaScript and CSS specifically for a single component

In my Angular 4 application, I have a specific component that requires the use of a js and css file. While most guidelines suggest placing these files in the Index.html file, I prefer to only load them when this particular component is accessed, not on e ...

JS backbone require global models in js

I am looking to implement a UserSession model that will handle loading and saving session IDs into cookies using the jQuery cookie plugin. Below is the code for my UserSession model module: define(['jQuery', 'Underscore', 'Backbo ...

How to verify changes in session variable using PHP and AJAX

Hey there! I'm looking for a way to continually monitor changes in a session variable within PHP. Let's say the session variable "x" starts off with a value of "1" and then, after five seconds, it changes to "2". This session variable "x" is up ...

Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string. Below is my attempted solution: var t = '1,234.04 km ...

Capturing the dynamic server response with nested JSON structures

I am in the process of creating a dynamic data-binding function named assemble that requires two input parameters: server response (JSON) - nested JSON object. instruction set (JSON) - a configuration object that dictates the binding. The Issue: The cur ...