1

So, what i want to make a simple web page that display multiple texts from an array one after one , I ve tried so many ways SetTimeout , Set interval and nothing work it give me only the last word like that the loop turn all times and give me the last result

<h1 class="name" id="text"></h1> html code
<script>
var cars = ["Saab", "Volvo", "BMW"];
var i  = 0 ;
setTimeout(function loop(){
do {
document.getElementById("text").innerHTML = cars[i];
i++;
}
while (i < cars.length);  
},4000)
</script>

9 Answers 9

1

Iterate the array and inside forEach callback use setTimeout.In that case there is no need of do & while loop.Since you want to display it once at a time with a delay , you need to change the timing value. You can do that by multiplying the index with constant time

var cars = ["Saab", "Volvo", "BMW"];
const element = document.getElementById("text");
cars.forEach((item, index) => {
  setTimeout(() => {
    element.innerHTML = item;
  }, index * 1000)
})
<h1 class="name" id="text"></h1>

Sign up to request clarification or add additional context in comments.

Comments

0

There are so many ways to do this. One is to use setInterval and iterate over the array of cars at each interval. And after the iteration go to the next value by incrementing the iterator with one.

The example below uses a closure to keep the iterator variable in its own scope.

const cars = ["Saab", "Volvo", "BMW"];
const textElement = document.getElementById("text");

function carDisplayer() {
  let i = 0;
  return function(cars) {
    let interval = setInterval(() => {
      if (i < cars.length) {
        textElement.textContent = cars[i];
        i++;
      } else {
        clearInterval(interval);
        i = 0;
     }
    }, 1000);
  }
}

let displayCars = carDisplayer();
displayCars(cars);
<h1 class="name" id="text"></h1>

Comments

0

if you use innerHTML with =, it replace new value.

So, 'text' element's innerHTML will be changed Saab->Volvo->BMW.

It's last word. right?

Try like this,

var cars = ["Saab", "Volvo", "BMW"];
let i  = 0 ;
setInterval(function loop(){
    document.getElementById("text").innerHTML += cars[i];
    i++;
},1000);

Comments

0

maybe you can set timer if there are car left to display

<h1 class="name" id="text"></h1> html code
<script>
var cars = ["Saab", "Volvo", "BMW"];
var i  = 0 ;

function displayCar() {
    document.getElementById("text").innerHTML = cars[i++];
    if (i < cars.length) {
        setTimeout(displayCar, 4000)
    }
}

setTimeout(displayCar, 4000)
</script>

Comments

0

var cars = ["Saab", "Volvo", "BMW"];
var i  = 0 ;
function loop() {
document.getElementById("text").innerHTML = cars[i];
    if (++i < cars.length) {
        setTimeout(loop, 4000);
    }
};

loop();
<h1 class="name" id="text"></h1>

Comments

0

Here is a possible solution:

var cars = ["Saab", "Volvo", "BMW"];
var i  = 0 ;
setInterval(function (){
document.getElementById("text").innerHTML = cars[i];
i++;
i = i%3;
}, 4000)
<h1 class="name" id="text"></h1>

The problem in your implementation was the do-while loop that iterates throught all elements at once.

If you use setInterval the whole function get's called every four seconds.

1 Comment

Please don't post your code to 3rd party sites as those links can die over time, making your answer meaningless. Just include your code right in your answer as a code snippet (the <> button on the toolbar).
0

here are both possible solutions. if you want to stop at the last one. or if you want to show keep it in loop.

<h1 class="name" id="text"></h1> html code
<script>
var cars = ["Saab", "Volvo", "BMW"];
var i  = 0 ;
let currentIndex = 0;
let inter_ = setInterval(function loop(){
   if(currentIndex >= cars.length){
       // if you want to loop  then the following line
       currentIndex = 0;
       // if you want to stop at the last one then uncoment the following lines
      // return clearInterval(inter_);
   }

   showCar();
   
}, 4000)


function showCar(){
    document.getElementById("text").innerHTML = cars[currentIndex++];
}

showCar()    

</script>

Comments

0

You can use an incremental timeout for different text. They will print in the different timelines.

var cars = ["Saab", "Volvo", "BMW"];
    cars.forEach((car, index) => {
      setTimeout(function loop() {
        document.getElementById("text").innerHTML = car;
      }, index * 2000)
    })
<h1 class="name" id="text"></h1>

If you want to learn async programming, You can do the same thing using async-await. Please have a look below example.

// Print function which prints after 1 sec.

  const print = (car) => {
      return new Promise(resolve => {
        setTimeout(() => {
          // Print here
          document.getElementById("text").innerHTML = car;
          resolve()
        }, 1000)
      })
    }

// Main function, Now consume it

async function main() {
  var cars = ["Saab", "Volvo", "BMW"];
  for (let index = 0; index < cars.length; index++) {
    await print(cars[index])
  }
}
main()

Working sample:

const print = (car) => {
  return new Promise(resolve => {
    setTimeout(() => {
      // Print here
      document.getElementById("text").innerHTML = car;
      resolve()
    }, 1000)
  })
}
async function main() {
  var cars = ["Saab", "Volvo", "BMW"];
  for (let index = 0; index < cars.length; index++) {
    await print(cars[index])
  }
}
main()
<h1 class="name" id="text"></h1>

Comments

0

Try this:

<h1 class="name" id="text"></h1> html code
<script>
    var cars = ["Saab", "Volvo", "BMW"];
    var i  = 0 ;
    const timer = setInterval(function () {
        if (i < cars.length) {
            document.getElementById("text").innerHTML += cars[i] + <br>;
            i++;
        }
        else {
            clearInterval(timer);
        }
    }, 4000)
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.