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:
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>