Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop is only displaying the last string in an array when adding it a span tag

I want to change the word in the span tag every 1.5 seconds but so far it is just displaying the last word in the array 'list'.

Here is my javascript

var list = [
    "websites",
    "user interfaces"
];


setInterval(function() {
for(var count = 0; count < list.length; count++) {
    document.getElementById("word").innerHTML = list[count];
}}, 1500);

And here is the html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <span id="word"></span>
</body>
</html>
like image 944
Jake123 Avatar asked Mar 04 '17 12:03

Jake123


1 Answers

You don't need a for loop, just use that setInterval, your counter or even simpler using Array manipulation:

var list = [
  "websites",
  "user interfaces",
  "cool neh?"
];

var count = 0; // Separate your count

function changeWord() { // Separate your concerns
  document.getElementById("word").innerHTML = list[count];
  count = ++count % list.length; // Increment and loop counter
}

changeWord();                  // First run,
setInterval(changeWord, 1500); // Subsequent loops
<span id="word"></span>

If you want to not use a counter but do it using array manipulation:

var list = [
  "websites",
  "user interfaces",
  "cool neh?"
];

var ELWord = document.getElementById("word"); // Cache elements you use often


function changeWord() {
  ELWord.innerHTML = list[0]; // Use always the first key.
  list.push(list.shift());    // Push the first key to the end of list. 
}

changeWord();                 
setInterval(changeWord, 1500);
<span id="word"></span>

P.S: The inverse would be using list.unshift(list.pop()) as you can see here.

Performance-wise the solution using counter should be faster but you have a small Array so the difference should not raise any concerns.

like image 133
Roko C. Buljan Avatar answered Oct 07 '22 01:10

Roko C. Buljan