How to use setTimeout inside for loop to change HTML objects every second?

How to use setTimeout inside for loop to change HTML objects every second?
0

#1

I have an array with words and I am trying to display each word for a short period of time.

Thats the code I have so far.

flashTime is set to 3000.

function setDelay(i)
{
    setTimeout(function(){
        console.log(singleWords[i]);
        document.getElementById('flash').innerHTML = singleWords[i];
    },flashTime);

    //setTimeout(function(){document.getElementById('flash').innerHTML = singleWords[i];},flashTime);    
}

function test()
{


}

function flashText()
{

    for(let i = 0; i < singleWords.length; i++)
    { 

       //setDelay(i);
       setTimeout(function(){document.getElementById('flash').innerHTML = singleWords[i];},flashTime); 

    }
}

The result I was expecting was for the paragraph in the html code to change every 3 seconds. Instead, judging by the console.log, the for loop executes after 3 seconds and then the paragraph changes to the last word in the array.

What is causing this?Thanks, hopefully nobody will get mad from my stupid question :smiley:


#2

Grrr im mad at your question. Jk

You forgot to set the interval in your setTimeout method. Use it as an argument in flashText function ie flashText(flashTime) or just set it directly

Keep the flashText function and delete everythign else


#3

Hi,

I implemented something similar a few weeks back, and i did it this way:

setInterval(changeImage, 5000); (changeImage is the function that loops through the images, if at the end, restart array element 0).

Does that help with your question?


#4

I just found this piece of code and it solved my problem. I just feel like cheating when I cant come up with clever solutions like this one, and jsut copy and paste…
I will try to solve it with both suggestions that I got.
If you guys have any ideas as to why my solution doesent work, or have any keywords I can google I will appreciate it. Its something to with javascript not supporting multithreading or idk…
Thanks.


function test()
{
    var i = 0;
    count = function() {
         document.getElementById("flash").innerHTML = singleWords[i];
         i++;
         if (i < singleWords.length) {
            window.setTimeout(count, 1000);
         }
    };
    count();
}