Tips for incorporating a time interval in every iteration of a for loop

I am attempting to display each word of a given text string on the screen at 60-second intervals. After some trial and error, here's what I have come up with:

let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  // Display words one by one.

  let textArray = text.split(" ");
  for(let i = 0; i < poemArray.length; i++) {
    mainId.textContent = poemArray[i];
  }  
}

I understand that I need to utilize the setInterval() method in this scenario, but I am unsure about the correct way to implement it. I have attempted placing the entire for loop within the function parameter of setInterval() and even tried putting the code inside the for loop itself as the function parameter, but nothing seems to be working.

Answer №1

Implementing a basic queue using shift and setInterval()

let words = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sed justo quis libero semper feugiat ac vel sapien.";

let container = document.getElementById("container");

function displayWords() {
  let wordsArray = words.split(" ");
  function showNextWord() {
    // get the first word from array and display it
    container.innerText = wordsArray.shift();
    // if there are still words left, set interval to display next one
    if (wordsArray.length) {
      setTimeout(showNextWord, 1000);
    }
  }
  showNextWord();
}

displayWords()
<div id="container"></div>

Answer №2

Create a new interval and assign it to a variable for easy clearing later on.

Use the .pop() method to remove the last element from an array and perform some action with it. Once the array is empty, stop the interval.

let myInterval = setInterval(() => {
    if (myArray.length > 0) {
        console.log(myArray.pop());
    } else {
        clearInterval(myInterval);
    }
}, 60000);

Answer №3

var mainId = document.getElementById("main");
var timeDelay = 1000; // in milliseconds
var text = "Greetings from a unique rewrite";

function displayText() {
    var textArray = text.split(" ");

    function ShowWord(item) {
      if (item < textArray.length) {
        mainId.innerText = textArray[item];
        setTimeout(ShowWord, timeDelay, item + 1);
      }
    }
    ShowWord(0);
}

displayText();
<div id="main"></div>

Answer №4

Your code contains a couple of errors that need to be addressed. To begin with, the variable `poemArray` should actually be named 'textArray'. Regardless, here is an alternative approach:

let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");
let textArray = text.split(" "); // Array of words

function displayWords() {
  if (textArray.length) { // If there are more words to display
    mainId.textContent += (textArray.shift() + " "); // Remove the first word and display it
    setInterval(displayWords, 1000); // Display the next word in 1 second
  }  
}
displayWords(); // Start the process by displaying the first word

Answer №5

If you want to introduce a custom delay using async/await, you can achieve it with the following code snippet:

const customDelay = ms => new Promise(resolve => setTimeout(resolve, ms));

function updateContent = async () => {
  let index = 0;
  const totalItems = contentArray.length;
  
  while (index < totalItems) {
    mainText.textContent = contentArray[index];
    index++;
    await customDelay(5000);
  }
};

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

JavaScript: Add an element to the precise middle of an array

Sorry if this is a repeat question, but I couldn't find the answer despite searching. Let's say there's an array of unknown length and you want to insert items at a specific position, such as the center. How can you achieve this? Here&apos ...

Determining whether an element possesses an attribute labeled "name" that commences with a specific term, apart from the attribute "value"

I'm planning to use distinctive data attributes with a prefix like "data-mo-". Let's say I have the following elements: <span data-mo-top-fade-duration="600">Title 1</span> <span data-mo-bottom-fade-duration="600">Title 2</ ...

Filter and select JavaScript objects based on the content of an array

I have a challenge filtering specific fields from a set of JavaScript objects: A= [{ asset_bubble: 17, biodiversity_loss: 15, code: "CH", critical_information: 14, cyber_attacks: 19, data_fraud: 13, de ...

Turning a JavaScript function into jQuery

Is there a way to convert this JavaScript selected code into jQuery? I need to target a button class instead of an ID, and I've heard that using jQuery is the simplest way to achieve this. var playButton1 = $('.playButton1'); playButton1.o ...

Is there a way to resolve the MongoDB Database-Differ Error?

I am currently working on creating an API and have set up a brand new Project, cluster, and Collection for it. However, when I attempt to use mongoose.save() to add data to my database, I keep receiving an error message. "message": { " ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

The functionality of using multiple inputs with Google Places API is not functioning as expected

Having trouble with the Google Place API. I am unable to set up 2 input fields with autocomplete. The first input is populated from a payload received from the backend, while the second input is within a Bootstrap modal. I have tried various solutions fou ...

JavaScript code that triggers a page refresh when an input is added to a form without actually inputting

Upon delving into extensive research on this particular subject, I regrettably came up empty-handed. My sincere apologies if this question has been posed before. The task at hand involves creating a form that prompts users to input information about four ...

Is it possible to use a Jasmine spy on a fresh instance?

In need of assistance with testing a TypeScript method (eventually testing the actual JavaScript) that I'm having trouble with. The method is quite straightforward: private static myMethod(foo: IFoo): void { let anInterestingThing = new Interesti ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...

Restricting data list values in AngularJS

Currently, I am facing a performance issue while trying to display approximately 2000 values retrieved through an API call using DataList in AngularJS. The page becomes extremely slow due to the large number of items being rendered. Is there a way to optim ...

What is a more efficient method for identifying a single, specific object without using the index approach demonstrated here?

I need to verify if the taskDetails object contains only the lastTask value and no other values. To achieve this, I am currently using the approach with index [0] as shown below: Object.keys(this.clubdetails.taskDetails)[0]==["lastTask"] However, I have ...

The script ceased functioning immediately following the inclusion of a case-insensitive search feature and interactive images

In the process of creating my inaugural project featuring a collection of images, I wanted to include a filter/search bar at the top. This bar would dynamically filter the displayed pictures based on user input. For example, typing "Aatrox" into the search ...

One helpful tip for adjusting the size of a UI chip on the fly

I am attempting to adjust the size of a UI chip dynamically based on the font size of its parent elements using the em unit in CSS. My objective is to achieve something like this: style={{size:'1em'}} The issue I'm encountering: The chip e ...

Different color for background of division

I am working with a structure that looks like this: <div class="wrapper"...> <a href="#"...>blah</a> <div class="post"...>stuff</div> </div> This structure repeats multiple times on a dynamic page. I am looking f ...

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...

Using the Selenium webdriver to reach the bottom of the page by scrolling vertically

Is there a way to determine if I have scrolled to the bottom of the page vertically? I have been using Webdriver and pressing the page down key repeatedly within a for loop, like so: for(int di=0; di<40; di++) { driver.findElement(By.tagName("body ...

Use Protractor to simulate Loss Connection by clearing LocalStorage in a Spec

Currently, I am utilizing the code window.localStorage.removeItem("name of localStorage variable you want to remove"); to eliminate two distinct localStorage Keys within a particular specification, and it is successfully removing them. Afterwards, I proce ...

Fill in input field based on choice from the drop-down menu - JavaScript

I am facing an issue where I cannot add text inside the text box based on the dropdown selection. For example, if I select option2 from the dropdown, the textbox should be populated with option2. (function() { 'use strict'; setInterva ...

Is the shift key being pressed during the onClick event in React?

To trigger an onClick event only when the meta(mac) / ctrl(win) key is pressed, follow these steps: This is what I attempted: const [shiftOn, setShiftOn] = useState(false) useEffect(() => { document.addEventListener('keydown', (e) => ...