javascript - Having difficulty with "For" loop + "setTimeout" logic -


basic premise of program trying send array of "http" request commands different servers.

my path of thinking create "for" loop , iterate through array 1 one sending batches of commands each server in array, having conflict appears "for" loop iterates way through , sends "http" request commands final server in array due "settimeout".

i appreciate if logic out can send batch of httpcmds each server while iterating through servers correctly.

here sample of code:

`

function sendhttpcmds(stbnum){     var stb_num = stbnum;     var xmlhttp; //cant make array of xml https      function xmlsend(cmd){         xmlhttp.open("get",http[cmd],false);         xmlhttp.send(null);         }             for(var = 0; < stb_num; i++){ //this first loop iterate through different servers        var http = stb_prop.http_list[i];        var httplength = http.length;        var lastipcmd = stb_prop.ip_list[i];         if(window.xmlhttprequest){           xmlhttp=new xmlhttprequest();        }else{           xmlhttp=new activexobject("microsoft.xmlhttp");        }      for(cmd = 0; cmd < httplength; cmd++){ //this second loop iterate through httpcmd list each server has        (function(cmd){             settimeout(function(){                 //main command sent 2 second intervals                 xmlsend(cmd);                               },2000*cmd);//set base delay ~1000-2500 ms         }(cmd));     } } 

}`

just clarify, stb_prop.http_list[i] array each element contains array of "http cmds". ex: stb_prop.http_list[0] = http_cmds[]

basically array within array (this because needed dynamically create list based on user input).

i see problem http variable

think happens, first loop starts, changes http , after exeuting few commands inner loop starts send requests. happens asynchronously though. imagine not executed until outer loop gone through 1 more time.

this goes on , if imagine none of async calls exectued before outer loop has completed, value of http set whatever last server was. async calls execute, use last value of http instead of own

a solution pass http anonymous called function way:

(function(cmd,http){             settimeout(function(){                 //main command sent 2 second intervals                 xmlsend(cmd,http);                               },2000*cmd);//set base delay ~1000-2500 ms         }(cmd,http)); 

and of course modify xmlsend take in http parameter.

let me know if works!


Comments