Home > Back-end >  How can I display names by using loop with setTimeout() function
How can I display names by using loop with setTimeout() function

Time:09-18

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>

CodePudding user response:

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>

CodePudding user response:

I think better solution for you here is to execute a function after 3 seconds, rather then putting the timeout inside for loop.

That was what was causing your issue, as the var is a function scoped variable. So by putting timeout inside of for loop, the last element would be undefined since your script would read the last element as arr.length, which is 4, and you don't have arr[4], hence it is undefined.

Also, your innerHTML was not written properly, if you want to print multiple values, you need to use innerHTML = instead of innerHTML = because innerHTML = will always print the last value from your loop, because it erases the innerHTML of your element in each new iteration.

I modified your code snippet below.

https://codepen.io/Juka99/pen/VwxpXwL

  • Related