Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I display names by using loop with setTimeout() function

I was trying to display members’ names in the div element after 3 seconds by using for loop with setTimeout() function. But I’m getting an undefined values of the names array. And even the value of var i displaying 4. I don’t know why. Can anyone explain to me why and how to fix that.?

Thanks in advance!

JS Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


function members() {
  var arr = ["Joseph","John","Kumar","Shiva"];
  var i;
  for(i = 0; i < arr.length; i++) {
    setTimeout(function() {
      console.log("Member = " + i + ". " + arr[i]);
      document.getElementById("Names").innerHTML = "Member = " + i + ". " + arr[i];
    }, 3000);
  }
}
members();

<div id="Names"></div>

>Solution :

First, Because var is a function scope ( not block scope like for loop ), when the setTimeout execute after 3 sec, the loop will be ended and the value of i will be equal to the arr.length, and arr[arr.lenght] will equal to undefined.

To solve this issue, one solution is using let instead of var.

Second, If you want to add the members to HTML, you need to use += to concatenate with the previous string not = which will re-initialize the innerHTML

const names = document.getElementById("Names");

function members() {
  var arr = ["Joseph","John","Kumar","Shiva"];
  for(let i = 0; i < arr.length; i++) {
    setTimeout(function() {
      console.log("Member = " + i + ". " + arr[i]);
      document.getElementById("Names").innerHTML += `Member = ${(i + 1)}. ${arr[i]}<br />`;
    }, 3000);
  }
}
members();
<div id="Names"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading