Итак, console.log распечатывает все из них, но сохраняется только последний сохраненный?
Поскольку вы перезаписываете его внутри l oop, и циклы выполняются как мгновенно (или действительно очень быстро, никак не заметить это на глаз). То есть, потому что есть для l oop, setInterval
вообще ничего не делает.
Что на самом деле происходит:
- Вы не делать: 1, подождать 5 секунд, 2, подождать 5 с и т. д. c.
- Вместо этого вы делаете: 1234, подождите 5 с, 1234, подождите 5 с и т. д. c.
Давайте рассмотрим пример решения в коде:
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();