遇到困难" For"循环+" setTimeout"逻辑

时间:2016-07-21 16:12:44

标签: javascript arrays for-loop settimeout

我的程序的基本前提是我正在尝试发送一个" http"请求命令到不同的服务器。

我的思路是创造一个" for"循环并逐个遍历数组,为数组中的每个服务器发送所有批处理命令,但是我遇到了一个冲突,它出现了" for"循环遍历并仅发送" http"由于" setTimeout"请求命令到数组中的最终服务器。

如果有人能够对此进行逻辑处理以便我可以正确地为每个服务器发送一批httpcmd,同时正确地遍历所有服务器,我将不胜感激。

以下是我的代码示例:

`

function sendHttpCmds(stbnum){
    var stb_num = stbnum;
    var xmlhttp; //cant make this an array of xml https

    function xmlsend(cmd){
        xmlhttp.open("GET",http[cmd],false);
        xmlhttp.send(null);
        }       

    for(var i = 0; i < stb_num; i++){ //this first loop is to iterate through the 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 is to iterate through the httpcmd list that each server has
       (function(cmd){
            setTimeout(function(){
                //main command sent with 2 second intervals
                xmlsend(cmd);                  
            },2000*cmd);//set base delay ~1000-2500 ms
        }(cmd));
    }
}

}`

为了澄清,stb_prop.http_list [i]是一个数组,其中每个元素都包含一个&#34; http cmds&#34;的数组。 例如: stb_prop.http_list [0] = http_cmds []

基本上是数组中的数组(这是因为我需要根据用户输入动态创建列表)。

1 个答案:

答案 0 :(得分:0)

我发现http变量存在问题

考虑一下发生了什么,第一个用于循环开始,更改http并在执行一些命令之后内部for循环开始发送所有这些请求。这虽然是异步发生的。所以想象它实际上并没有被执行,直到外部for循环再次经历。

这继续,如果你想象在外部for循环完成之前没有异步调用被激活,http的值将被设置为最后一个服务器。现在所有的异步调用都会执行,但它们都使用http的最后一个值而不是它们自己的

解决方案可能是以这种方式将http传递给匿名调用函数:

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

当然修改xmlsend以接受http参数。

让我知道它是否有效!