Friday, June 22, 2018

javascript - 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    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



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    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 StartInterval(myparam[i], myfrequency[i])
}





No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...