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