Jake123
Jake123

Reputation: 181

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>

Upvotes: 7

Views: 358

Answers (5)

KooiInc
KooiInc

Reputation: 122916

Better use setTimeout. Every iteration should have its own timeout. See also

(() => {
  const words = document.querySelector('#words');
  typeWords([
      "web sites",
      "user interfaces",
      "rare items",
      "other stuff",
      "lizard sites",
      "ftp sites",
      "makebelief sites",
      "fake news sites",
      "et cetera"
  ]);

  function typeWords(list) {
    list.push(list.shift()) && (words.innerHTML = list[list.length-1]);
    setTimeout(() => typeWords(list), 1500);
  }
})();
<div id="words"></div>

Upvotes: 0

Redu
Redu

Reputation: 26161

I would do this job by setTimeout() as follows,

function loopTextContent(a, el, dur = 1500){
  var  i = -1,
     len = a.length,
    STID = 0,
  looper = _ => (el.textContent = a[i = ++i%len], STID = setTimeout(looper,dur));
  looper();
  return _ => STID;
}

var list = ["websites", "user interfaces", "user experience", "whatever"],
 getSTID = loopTextContent(list, document.getElementById("word"));
setTimeout(_ => clearTimeout(getSTID()),10000);
<span id="word"></span>

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

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.

Upvotes: 2

Manoj Mohan
Manoj Mohan

Reputation: 662

The problem with your code is whenever your interval function is called,loop get executed and prints the element because you are replacing the whole innerHtml on each iteration. You can try the following code if u want to print whole list element again and again after interval.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<span id="word"></span>
</body>

The javascript code :

  var list = [
"websites",
"user interfaces"
];
var count=0;
function print()
{
  document.getElementById("word").innerHTML = list[count];
count += 1;
count%=list.length;
}
setInterval( print(), 1000);

Upvotes: -1

Mazz
Mazz

Reputation: 1879

You may wanna try this. Not looping, just calling a changeWord function every 1.5 sec.

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

    function changeWord() {
        document.getElementById("word").innerHTML = list[count];
        count = count < list.length-1 ? count+1 : 0;
    }

    setInterval(function() { changeWord(); }, 1500);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <span id="word"></span>
</body>
</html>

Upvotes: 0

Related Questions