Saxman13 Saxman13 - 6 months ago 30
Javascript Question

calling multiple setInterval() functions in js with a loop

I'm new to javascript and I'm having trouble using the setInterval() function properly.

Basically I want to call a function at different given intervals for different parameters both of which I have in lists.

I have a function called myfunction. I have a list called myparam with all of the variables I want to pass this function. And finally I have a list called myfrequency which is the time in millis that I want between each call of myfunction with the parameter given in myparam. I'm trying something like this but it's not working:

for(i=0;i<myparam.length();i++;){
setInterval(function(){myfunction(myparam[i]);},myfrequency[i]);
}


The result of the above code is that it works only for the last index. myfunction gets called at the correct interval with the correct parameter for ONLY the last value in myparam.

Why does this happen? Is my thinking that setInterval() sets up the calling of a function at an interval incorrect?

Answer Source

Well it's because setInterval has a delay which means when the interval runs the loop is already been finish

To do that just create another function which will start your interval

function StartInterval(index, frequency) {
    setInterval(function(){
        myfunction(index);
    },frequency);
}

Then inside your loop just call this function and pass something

for(i=0;i<myparam.length;i++){
    StartInterval(myparam[i], myfrequency[i])
}

   
/** set what value you want **/
var myparam = [10,20,30];
var myfrequency = [1000,2000,3000];


function myfunction(index) {
  console.log(index);
}

function StartInterval(index, frequency) {
  setInterval(function(){
    myfunction(index);
  },frequency);
}

for(i=0;i<myparam.length;i++){
  StartInterval(myparam[i], myfrequency[i])
}