pause in execution between iterations of a for loop

Challenge

I'm currently working on a function that processes a list of strings by printing each one on a new line, with CSS animations that gradually display the string over a few seconds. However, I'm struggling to make sure that the next string's animation only starts once the previous one has finished entirely. Below is a snippet of my code - hope it helps clarify my issue.

Desired Outcome

My goal is for the newComputerMessage(messages) function to display each string from the array on a new line only after the previous one has been fully displayed.

let userInputs = [];
const textBox = document.querySelector(".textBox");
const userInput = document.querySelector(".userInput");
const letters = /^[A-Za-z]+$/;
let user = {
  name: "",
  timeInterval: -1,
  halt: false,
  quit: false
};

function captureUserInput() {
  let text = userInput.value;
  userInput.value = "";
  return text;
}

function nameEntered() {
  enteredName = captureUserInput();
  if (!enteredName.match(letters)) {
    newComputerMessage(">>Please only use Letters");
  } else {
    user.name = enteredName;
    newComputerMessage([">>Hello there " + user.name, ">>Second message"]);
  }
}

function newComputerMessage(messages) {
  for (let index = 0; index < messages.length; index++) {
    const newPElement = document.createElement("p");
    newPElement.innerHTML = messages[index];
    newPElement.setAttribute("class", "computerText");
    textBox.appendChild(newPElement);
  }
}
.textBox {
  width: max-content;
}

.computerText {
  color: black;
  font-family: monospace;
  overflow: hidden;
  border-right: 0.15em solid orange;
  white-space: nowrap;
  margin: 0 auto 0 0;
  letter-spacing: 0.15em;
  animation: typing 3.5s steps(30, end), blink-caret 0.5s step-end infinite;
  width: max-content;
}

/* The typing effect */
@keyframes typing {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from,
  to {
    border-color: transparent;
  }
  50% {
    border-color: orange;
  }
}
<body>

  <div class="displayScreen">
    <div class="textBox">
      <p class="computerText">>>Hello, please enter your name below</p>
    </div>

  </div>

  <div class="appInput">
    <input class='userInput' type="text" name="fname"><br>
    <input onclick="nameEntered()" class="button" type="submit" value="Submit">
  </div>
  </div>

</body>

Answer №1

If you want to implement a setTimeout function, check out the example below. The first snippet is a demonstration of how it works, while the second snippet shows how you can incorporate it into your code:

I chose to use a time interval of 3500 milliseconds based on the observation of 3.5s as the duration of your animation in the CSS. Feel free to adjust this value to suit your requirements.

function newComputerMessage() {
  for (let index = 0; index < 3; index++) {
    setTimeout(() => console.log('appending element'), 3500 * index);
  }
}

newComputerMessage();

Therefore, in the context of your code, it would be:

function newComputerMessage(messages) {
  for (let index = 0; index < messages.length; index++) {
    const newPElement = document.createElement("p");
    newPElement.innerHTML = messages[index];
    newPElement.setAttribute("class", "computerText");
    setTimeout(() => textBox.appendChild(newPElement), 3500 * index);
  }
}

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

Dynamic item addition feature activated by button on contact form

I am looking to create a form that includes the standard name, phone, email fields as well as a dropdown for selecting products and a text box for inputting quantity. The unique aspect is allowing users to add multiple products (dropdown and quantity textb ...

Tips for invoking the export function in node.js using sequelize

Need help with calling the function (search_all_user) to export in node.js using sequelize module.exports = function (sequelize, Sequelize, DataTypes) { var User = sequelize.define('user', { id: {type: Sequelize.INTEGER, unique: true, prima ...

Separate JavaScript/ASP statements using commas

I'm having trouble comma-delimiting this line in JavaScript, as I keep encountering errors: <a href="javascript:doSubmit(<%= pound & rs("AdvertiserID")%>, <%=rs("AdvertiserName")%>)"> It's Friday, what can I say... The &l ...

"Having trouble with sound in react-native-sound while playing audio on an Android AVD? Discover the solution to fix this

react-native-sound I attempted to manually configure react-native-sound but I am unable to hear any sound. The file was loaded successfully. The audio is playing, but the volume is not audible on Android AVD with react-native-sound. ...

Having trouble compiling your Vue project and running into the "No mixed spaces and tabs" error?

Below are the details with an error: Error Details: Failed to compile. ./src/components/Header.vue Module Error (from ./node_modules/eslint-loader/index.js): H:\project\VueProjects\stock-trader\src\components\Header.vue 27: ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...

Track when a user modifies a <select> dropdown list generated using the Jquery method ".html()"

Is it possible to detect a change in the value of a select list when that select list has been added using either the .html(htmlString) or .append(content[,content]) jQuery function? HTML CODE: <ul class="htmlClass"> <!-- Populated via JS --& ...

Breaking or wrapping lines in Visual Studio Code

While working in Visual Studio Code, I often encounter the issue of long lines extending beyond the screen edge instead of breaking and wrapping to the next line. This lack of text wrapping can be quite bothersome. I utilize a split-screen setup on my co ...

JavaScript validation for radio buttons that are grouped together

Need help with a JavaScript validation issue regarding grouped radio buttons named optionRadios1 to 5. I'm trying to validate them before submitting the form, but my code isn't working as expected and still allows the form submission. Below is t ...

Is there a way for me to manage the appearance of the printed document's layout?

I have successfully added 3 print buttons to my website, each one designed to print a specific portion (div) of the webpage. Here is the code snippet for this functionality: function printPage(id) { var html="<html>"; //html+="<link rel="st ...

Is there a way to determine if a specific JSONArray is contained within my existing JSONArray?

I am faced with the challenge of parsing a JSONArray that may or may not include an "attachmentPoint" element. Here is an example of the JSONArray structure: [{"entityClass":"DefaultEntityClass","mac":["86:2b:a2:f1:2b:9c"],"ipv4":["10.0.0.1"],"ipv6":[], ...

How can one discern the most effective method to identify JavaScript code that alters particular HTML content on a webpage?

On my website, I have a <p> tag and I am interested in knowing which JavaScript function is responsible for adding text inside this element. Is there a special method in Chrome to add a listener on this tag and pinpoint the script that writes to it ...

Attempting to bundle js files using Browserify, but encountering issues with require('jquery-datetimepicker') not functioning correctly

For bundling my javascript file, I rely on gulp + browserify. I start by running npm install select2 --save require("select2"); module.exports = { init: function() { $('#datetime-start').datetimepicker({ dayOfWeekStart : ...

Assessing the validity of a boolean condition as either true or false while iterating through a for loop

I am facing an issue that involves converting a boolean value to true or false if a string contains the word "unlimited". Additionally, I am adding a subscription to a set of values and need to use *NgIf to control page rendering based on this boolean. &l ...

Maintain uniform product dimensions for images and configurable swatches in Magento

I am new to using Magento and I am currently working on setting a consistent product image grid size of 500px x 500px for the product detail page. Some of my product images are in square or rectangular shapes, so I need to resize them to fit into the grid ...

The filter search feature fails to return any results when data is inputted into the tables

I have implemented a filter search feature within two tables on my website. My goal is to retrieve the search results for a specific drink while keeping the table headings fixed in their positions. For instance, if I type "Corona" into the search box, I ...

Updating a URL once AngularJS has finished processing it

Currently, I am utilizing Primo, an AngularJS app developed by Ex Libris. This application functions as a library catalog, enabling users to explore both physical and digital collections within the library. Despite not having direct access to the original ...

Bot on Discord engaging in a gaming session

I recently developed a Discord bot with the status of ""playing a game"" and here is the code that I implemented: bot.on('ready', () => { console.log('Client is online!'); bot.user.setActivity('osu!'); Th ...

Can the color scheme be customized for both light and dark themes in Ant Design version 5?

After creating a hook that successfully toggles between light and dark modes in Chrome's Rendering panel, I noticed that the values in the ConfigProvider remain unchanged when switching themes. Can anyone suggest a workaround to modify the design toke ...

Displayed unfamiliar Obj characters on Google Chrome

Hey there, I'm new to Vue JS and Vuetify and could really use some help! I've been trying to display some HTML content from my data using v-html in Vue JS, but for some reason, strange OBJ symbols keep showing up. Here is a screenshot of what I ...