0

Still pretty new to this so forgive me something is not correct. I have an array with different strings of text, and I want to list each string in an html div with a 2 second delay between each line of text. I figured out how to display the whole array to the div element in html. However, I am having trouble trying to wrapping my head around how to add the 2 second delay affect. Any help would be greatly appreciated.

JS file -

var arrText = [
  "display after 2 seconds", "display after 4 seconds", "display after 6 seconds", "display after 8 seconds",
];
var html='';
for (var i=1; i < arrText.length; i++) {
    html+='<div>'+arrText[i]+'</div>';
}
document.getElementById('text-list').innerHTML+= html;

html file-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>delay test</title>
</head>
<body>
     <div>
       <div id="text-list" class="home-div"></div>
     </div>
    <script src="textScript.js"></script>
</body>
</html>

1 Answer 1

1

It's pretty forward. After you create your string array.

var arrText = ["display after 2 seconds", "display after 4 seconds", "display after 6 seconds", "display after 8 seconds"];

Use setInterval function to execute the code every 2000ms.
(Check console for results)

var i = 0;
var interval = setInterval(function() {
  if (i < arrText.length) {
    var div = document.createElement('div');
    div.innerHTML = arrText[i];
    document.body.appendChild(div);
    console.log(div)
    i++;
  } else {
    clearInterval(interval);
  }
}, 2000);

Now, whatever gets inserted to your string array will be printed out after 2 seconds wrapped in an html <div> blocks.

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

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.