0

I have a doubt regarding the setInterval function. I am trying to read the JSON file and send email to all the email id's within that JSON,But the problem is only the last email id pass to the sendtheMail() function. Therefore email send only to the last email id. below you can see my code , Please can anyone help me with this issue

async function mailSend(callback) {

    for (let scriptData of automatedScriptData.dataList) {
        var userData = {
            email: scriptData["Business Email"],
            password: "acc0unt@123",
            name: scriptData["First Name"] + " " + scriptData["Last Name"],
            firstName:scriptData["First Name"],
            title: scriptData["Title"],
            timeZone: scriptData["Time Zone"],
            location: scriptData["Country"],
            company: scriptData["Company"]
        };

       setInterval(function() {
         console.log(userData.email);
           sendtheMail(userData);
           }, 5*1000); 

    }

}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Manoj Prasanna
  • 156
  • 1
  • 10

1 Answers1

0

Javascript is single-threaded and it has an event loop

enter image description here

Your function has a cycle and upon each iteration, an event is added to the event loop. However, since var variables are function-scoped, the variable is overriden in each iteration of the cycle and then, the function you defined in timeout is called, but by then your variable has taken its value. Change var userData to let userData, because let is block-scoped and that's what you need here. Sample example to prove my point:

for (var i = 0; i < 2; i++) {
    let foo = i;
    setTimeout(function() {console.log("foo is " + foo)}, 100);
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175