-1

I am new to JavaScript.

What I want to do is print the elements of an array one by one on the same location, but after a specific time interval.

Here it prints only the last element.

<!DOCTYPE html>
<html>
<head>
  <title>sample</title>
</head>

<body>
  <p id="test"></p>

  <script>
  const words = [ "Word1" , "word2" , "word3" , "word4" ];

  for (let i = 0; i < words.length; i++ ) { 
    console.log(words[i]);
    setTimeout(function(){  document.getElementById('test').innerHTML = words[i]; }, 2000);
  }
  </script>
</body>
</html>
Dave Newton
  • 158,873
  • 26
  • 254
  • 302

2 Answers2

1

You can try this,it prints all one after the other

const words = ["Word1", "word2", "word3", "word4"];
for (let i = 0; i < words.length; i++) {
  console.log(words[i]);
  setTimeout(function() {
    document.getElementById('test').innerHTML += words[i];
    document.getElementById('test2').innerHTML = words[i];
  }, 2000 * i);
}
<!DOCTYPE html>
<html>

<head>
  <title>sample</title>
</head>

<body>
  <p id="test"></p>
  <p id="test2"></p>

</body>

</html>
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
0

You are using the wrong function.

A timeout just pauses the script for a period of time, what you are looking for is setInterval.

<!DOCTYPE html>
<html>
  <head>
    <title>sample</title>
  </head>
  <body>
    <p id="test"></p>
    <script>
      const words = ['Word1', 'word2', 'word3', 'word4'];

      i = 0;
      const counter = setInterval(foo, 1000);

      function foo() {
        document.getElementById('test').innerHTML = words[i];
        i++;
        if (i >= 4) clearInterval(counter);
      }
    </script>
  </body>
</html>
Cedervall
  • 1,309
  • 2
  • 13
  • 20