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

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)
        document.getElementById('flash').innerHTML = singleWords[i];

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

function test()


function flashText()

    for(let i = 0; i < singleWords.length; 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:

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

1 Like


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?

1 Like

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…

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