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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With