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

JavaScript Pause Loop After Three Iterations

I’m trying to get my program to pause after every three iterations, but instead, it’s looping through the entire list, pausing, and then only logging the numbers in the list that are divisible by three. I’m clearly not thinking about this correctly and would greatly appreciate some insight.

What I’d like to happen is…
one
two
three
(pause for 3 seconds)
four
five
six
(pause for 3 seconds)
etc.

Here’s what I’ve been working on:

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

 let sendingList = [
  'one',
  'two',
  'three',
  'four',
  'five',
  'six',
  'seven',
  'eight',
  'nine',
  'ten',
  'eleven',
]

function sendMail(counter) {
  sendingList.forEach(element => {
    counter++;
    console.log(counter)
    if (counter % 3 === 0) {
      setTimeout(function() {
        console.log(element)
      },3000)
      // console.log(counter)
    }
  })
}

sendMail(0)

>Solution :

Try using recursion:

 let sendingList = [
  'one',
  'two',
  'three',
  'four',
  'five',
  'six',
  'seven',
  'eight',
  'nine',
  'ten',
  'eleven',
]

function sendMail(counter) {
    if (counter >= sendingList.length) return;
    if (counter > 0 && counter % 3 === 0) {
        setTimeout(function() {
        console.log(sendingList[counter]);
      sendMail(counter+1);
        },3000);
  } else {
      console.log(sendingList[counter]);
      sendMail(counter+1);
  }
}

sendMail(0)
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