Troubleshooting: Issue with setInterval not looping over array

An issue has arisen where the loop is only displaying the last value of the array, which is 'o'

const h2 = document.querySelector('h2');
const title = document.querySelector('h1');

const word = ['h', 'e', 'l', 'l', 'o'];

function loopThroughWords() {
    for(let i = 0; i < word.length; i++) {
        window.setInterval(() => {
            console.log(word[i]);
            title.textContent = word[i];
        }, 1000)
    }
}

loopThroughWords();
<h1 />
<h2 />

Answer №1

When dealing with a small number of intervals, my recommendation is to utilize the setTimeout function instead. Assign appropriate timeouts and create a closure over the desired character to add to the innerHTML property of the element.

function textEffect(text, element) {
    for (let i = 0; i < text.length; i++) {
        setTimeout((char => () => element.innerHTML += char)(text[i]), (i + 1)* 1000);
    }
}

textEffect('hello', document.querySelector('h1'));
<h1></h1>

If you still prefer using setInterval, remember to keep track of the interval and clear it once the word is fully displayed.

function textRoll(text, element) {
    var interval = setInterval((i => () => {
        if (i >= text.length) return clearInterval(interval);
        element.innerHTML += text[i++];
    })(0), 1000);
}

textRoll('hello', document.querySelector('h1'));
<h1></h1>

Answer №2

The reason for this issue is that the interval is happening inside the loop, causing the variable i to reach the end of the array by the time it reaches 1.

Do you think this modification aligns with your intentions?

let i = 0;
let interval;

const loop = () => {
  console.log(word[i]);
  if (word[i]) title.textContent += word[i];
  else clearInterval(interval)
  i ++;
}

interval = window.setInterval(loop, 1000);

I trust this clarifies things for you.

Answer №3

To modify the title of all words in an array after 1 second, you can begin by targeting index 0 and repeatedly using setInterval until the index is less than the word's length.

For example:

const h2 = document.querySelector('h2');
const title = document.querySelector('h1');

const word = ['h', 'e', 'l', 'l', 'o'];

loop(0);

function loop(index) {
  setTimeout(() => {
    if (index < word.length) {
      title.textContent = word[index];
      setTimeout(() => loop(index+ 1), 1000);
    } else {
    setTimeout(() => loop(0), 1000);
    }
  }, 1000)
}

In this code snippet, I am assigning the first element, then setting a setTimeout for the next one.

If the index surpasses the length of the word, I have included an 'else' statement to reset the word loop.

Answer №4

From what I gather, the objective of this program is to add the word hello every second.

I have found success with this code

html

<h1 />
<h2 />

js

const h2 = document.querySelector('h2');
const title = document.querySelector('h1');

const word = ['h', 'e', 'l', 'l', 'o'];

function loop() {
   for(let i = 0; i < word.length; i++) {
       window.setInterval(() => {
            console.log(word[i]);
            title.textContent += word[i] ;
       }, 1000)
    }
}

loop();

Check out the demo:

https://jsfiddle.net/Danielprabhakaran_N/sjzrx3qy/

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

Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway. https://i.stack.imgur.com/S5Zx9.png Both FastAPI and API Gateway have CORS enabled, b ...

Utilize the sendKeys method to input text and save the entered value in

Currently, I am using WebdriverJS to interact with a form. In my test, I want to open the form, fill in a field using sendKeys, and then store this value in a variable. Here is the code snippet: driver.findElement(By.xpath("//a[contains(text(),'Añad ...

Issue specific to iOS devices: AJAX-loaded HTML containing <script> tags fails to execute

The purpose of the code below is to import innerStuff.html into the content-container div. Once that is done, a script within innerStuff.html named submit_entry() is used to submit the form in innerStuff.html. Current Situation: Upon clicking the button, ...

The utilization of $(this) proves to be ineffective

I've been working on getting a script to add events to a specific DIV within a class using pep.js: $( ".drag" ).pep({ start: function() { $(".drag").addClass('color'); $('.drag').next(".text").fadeIn("slow"); ...

Enhance your Vuetify v-data-table with intricate data integration

I am currently working on the v-data-table component and I'm having trouble processing information from the backend. Can anyone provide some assistance? I attempted to use this code, but I keep receiving the error: "vue.runtime.esm.js:1897 TypeError: ...

Break free from the confines of a single quote in jQuery within

I'm currently facing a challenge with my ajax function that calls a PHP class to retrieve code stored in the variable $var. The issue arises from having single quotes within the $var string, causing JavaScript to throw an error. Is there a more effic ...

Is it possible to have a field automatically calculate its value based on another field?

Consider the following data structure: { "rating": 0, "reviews": [ {"name": "alice", rating: 4}, {"name": "david", rating: 2} ] } What is the best way to recalculate the overall rating when new reviews are added or existing reviews are upda ...

The error message indicates a type mismatch: it is not possible to convert from a double[][]

As a beginner in Java, I recently encountered this problem that I couldn't find a solution for after searching extensively. public class Cliente{ private int clientID; private String clientName; private double clientDebt; private dou ...

`How can a timer be removed from memory?`

Does the memory allocated for timers set using window.setTimeout get deleted immediately after the callback function completes its execution? ...

Using Vue 3's emit in place of v-model

I am facing a challenge with integrating a custom dropdown select component. The idea is to use v-model to retrieve data from the parent component, but I am unsure how to pass that through an emit. Can anyone clarify this for me? Here is my parent compone ...

Getting AJAX to function on a local server with either XAMPP or node.js

I am completely stumped and in need of some assistance. My current challenge involves trying to implement AJAX on a local server, but I am feeling lost when it comes to even the most basic coding. I have installed node.js and XAMPP to my system and have b ...

Sweet treats, items, and data interchange format

Can an object be converted to a string, stored in a cookie, retrieved, and then parsed back to its original form when the user logs on again? Here's a concise example of what I'm asking: var myObject = { prop1: "hello", prop2: 42 }; va ...

Slide your finger to adjust the location of a 3D model within the Three.js environment

Having trouble with a three.js example that allows me to rotate, zoom in, and zoom out a 3D object, but I can't figure out how to change its position by dragging. Any assistance would be greatly appreciated. Check out the example here. ...

Encountered an error with AngularJS $http.post - Unexpected token F

I've encountered an issue while running my $http.post script and have been searching for a solution without success. Below is the error that appears when I try to run the webpage: XHR finished loading: POST "http://mypage/services/json/DownTimeStartB ...

Synchronizing two dropdown menus in Angular

I'm having trouble with binding and synchronizing select elements. I am trying to make two select elements work together, but using ng-value="$index" doesn't seem to be doing the trick. These are in sync: <select ng-model="myVar1"><op ...

Embed the variable directly within the JSON structure

My goal is to dynamically create a JavaScript object using object initializer notation, but with keys taken from a config object. Instead of the traditional method: var obj = { 'key' : 'some value' }; I envision something like this: ...

Arranging Alphanumeric Characters in Typescript

Given input -> const s = ['2.1.1.a', '2.1.a', '2.1.1.d', 'A2.2', 'A2.1', 2.1.1.c', '2.1.b', '2.1.1.b'] Expected output after sorting -> const s = ['2.1.a', '2. ...

Error encountered while trying to process a CSV file due to Unicode decoding issue

Out of nowhere, a "UnicodeDecodeError" pops up in my code that was working just fine yesterday. File "D:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 3284, in run_code self.showtraceback(runnin ...

The higher-order component is lacking a defined display name in its definition

Struggling to develop a higher order component, I keep receiving an eslint warning. The component definition is missing a display name. Even after attempting to include a display name as shown below, the warning persists. import React from 'react ...

When the React js application is opened in a hosted environment, the CSS styling may be overridden

My React js application is hosted within another application. When a jQuery dialog opens, the React application also launches. While the functionality works correctly, some of the CSS styles are appearing incorrectly. I suspect that either the CSS from the ...