Alanaj
Alanaj

Reputation: 247

Looping through array and only getting last item?

I am trying to loop through colors for my background with javascript but it only returns the last item, blue.

I've tried to look through different answers on this website but I'm new to javascript and couldn't understand what they are saying. Does anyone have an answer?

function background() {
  const bg = document.querySelector('header');
  const colors = ['red', 'orange', 'yellow', 'blue'];

  for (let i = 0; i < colors.length; i++) {
    console.log(colors[i])
    bg.style.backgroundColor = colors[i];
  }
}

background();
setInterval(background, 5000);
<header style="width:100px; height:100px"></header>

Upvotes: 0

Views: 124

Answers (6)

n-smits
n-smits

Reputation: 713

So the console.log prints out all of them, but only the last remains saved?

Because you're overwriting it inside the loop, and loops run like instantly (or really really fast, no way you could spot that by eye). Meaning, because there is a for loop, the setInterval is not doing pretty much anything at all.

What's actually happening:

  • You're not doing: 1, wait 5 seconds, 2, wait 5s etc.
  • Instead you're doing: 1234, wait 5s, 1234, wait 5s etc.

Let's see an example solution in code:

let i = 0;
// move variable i out of the function
// so it is not reset every time the function is run

function background () {
    // your code, nothing new here
    const bg = document.querySelector('header');
    const colors = ['red', 'orange', 'yellow', 'blue']
    bg.style.backgroundColor = colors[i];

    // then to have it change
    if (i < (colors.length) { i++; } // increase i+1 until we have reached max
    // i++ is shorthand for i = i + 1
    else i = 0;
    // and if have, reset it (that's why it is outside the function)
    // if it were inside it, it would reset every time the function runs
}
setInterval(background, 5000);
background();

Upvotes: 3

PixelWolfe
PixelWolfe

Reputation: 13

It has to do with your for() loop,

You are looping through all indexes of your array holding the colors and setting bg.style.backgroundColor = colors[i], but then the for() loop notices that i is still < array.length, so it continues to the next color near instantly.

Its only showing the last value of 'blue' since its the end of the loop. :) Your run condition of the for loop doesn't stop until it reaches that.

Maybe increment the array value instead of looping through it. Not sure of the best way to do that yet though.

(New to programming though, so listen to the other guys first, literally just made a Stack Overflow account 5 minutes ago haha)

Upvotes: 1

BraylanBB121
BraylanBB121

Reputation: 35

You are only getting the last one because you need to use the setTimeout() function or the setInterval() function. It only returns the last one because when it loops it goes all the way until the last one, without stopping.

Upvotes: 0

Anirudh Kanukanti
Anirudh Kanukanti

Reputation: 318

Are you looking to change the background color every 5 seconds? In that case use the below code snippet

var colorIndex = 0;

function background() {
  const bg = document.querySelector('header');
  const colors = ['red', 'orange', 'yellow', 'blue']

  bg.style.backgroundColor = colors[colorIndex++];

  //resetting the index to 0 to repeat the colors after reaching end of colors
  if (colorIndex >= colors.length) {
    colorIndex = 0;
  }
}

setInterval(background, 5000)

background();
<header style="width:100px; height:100px"></header>

Upvotes: -1

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6418

I think you are hoping something like this-

var colorIndex = 0;

function background () {
    const bg = document.querySelector('.header');
    const colors = ['red', 'orange', 'yellow', 'blue'];
	bg.style.background = colors[((colorIndex++) % colors.length)];
}

background();
setInterval(background, 1000);
.header {
  width: 100px;
  height: 150px;
  background: gray;
}
<div class="header"></div>

Note: The line ((colorIndex++) % colors.length) means I declare an index variable named colorIndex = 0 and increment at each interval and if it exceeded the colors array length then make it zero again by modulo it by the colors.length.

Upvotes: 1

norbitrial
norbitrial

Reputation: 15176

I would implement the function without the for loop. Instead you can increment on each function call the indexer value. Once you achieved the last item, reset the value to zero and start from the beginning. So technically you can think about setInterval in this case like your loop but you need to handle the indexer value on each iteration.

Try as the following:

let i = 0;

function background () {
    const bg = document.querySelector('header');
    const colors = ['red', 'orange', 'yellow', 'blue']
    bg.style.backgroundColor = colors[i];
   
    if (i === colors.length - 1) i = 0;
    else i++;
}

setInterval(background, 1000);

background();
<header>This is the header</header>

I hope this helps!

Upvotes: 0

Related Questions