Search code examples
javascriptasynchronouses6-promise

loop in js, but wait till current iteration is done, then get to next


My goal is to execute a function that can print number 1-4; But in 1s intervals (and I don't want to use setInterval). I've been trying and what I could do was to print all the elements in an array after one second delay. here's the code :

const wait = async (number) => {
  return new Promise(async(resolve)=>{
    setTimeout(async()=>{
      resolve();
    },number);
  })
}

const listElement = document.getElementById("list");

[1,2,3,4].map((num)=>{
  const newListItemElement = document.createElement("li");
  newListItemElement.innerHTML = num;
  wait(1000).then(()=>{
    console.log(num);
    listElement.appendChild(newListItemElement);
  })
})
<html>
<body>
  <h3>list</h3>
  <ul id="list">
  </ul>
</body>
</html>

What I want this to do is to wait a second and print 1 then wait a second and print 2 and so on. The code I added in the snippet is making all the numbers appear together at once and this is because map function goes on even if the current iteration isn't done yet.


Solution

  • You can do this using setTimeout

    const listElement = document.getElementById("list");
    
    [1, 2, 3, 4].forEach((num) => {
      setTimeout(() => {
        const newListItemElement = document.createElement("li");
        newListItemElement.innerHTML = num;
        listElement.appendChild(newListItemElement);
      }, num * 1000);
    })
    
    const listElement2 = document.getElementById("list2");
    
    // use this if you are looping over an array of data instead of array of numbers
    [1, 2, 3, 4].forEach((num, index) => {
      setTimeout(() => {
        const newListItemElement = document.createElement("li");
        newListItemElement.innerHTML = num;
        listElement2.appendChild(newListItemElement);
      }, (index + 1) * 1000);
    });
    <body>
      <h3>list</h3>
      <ul id="list">
      </ul>
        <h3>list 2</h3>
      <ul id="list2">
      </ul>
    </body>