2013-05-03 38 views
0

这里是我的代码部分:如何在setInterval循环中设置延迟?

$('#monitor').click(function(){ 
      setInterval(function(){ 
        $('#status_table tr [id^="monitor_"]:checked').each(function() { 
         monitoring($(this).parents('tr')); 
        }); 
       },15000); 
     }); 

我想打电话给每一行的功能monitoring在具有其对应的复选框选中的表。如果我只有一个,它工作正常。但是当我有一个以上的时候,它会乱七八糟,这意味着它不会在表中追加正确的状态。 这里是我的功能monitoring

 function monitoring($row) { 
      fbType = $row.find('td:nth-child(3)').html(); 
      fbNum = $row.find('td:nth-child(4)').html(); 
      eachStatus =$row.find('td:nth-child(5)').attr('id'); 
      $('#ptest').append(fbType + ' '+ fbNum+' '+ eachStatus +'<br>'); 

      $.post('/request', {inputText: fbNum,key_pressed: fbType.toString()}).done(function (reply) { 
       if (reply == "on") { 
        $('#status_table tr #'+eachStatus).empty().append("on"); 

       } else if (reply =="off") { 
        $('#status_table tr #'+eachStatus).empty().append("off"); 

       } 
      }); 
     } 

我如何可以延迟函数调用的每一行?我试图#ptest显示undefined以下

 $('#monitor').click(function(){ 
      setInterval(function(){ 
        $('#status_table tr [id^="monitor_"]:checked').each(function() { 
         setTimeout(function(){ 
          monitoring($(this).parents('tr')); 
         }); 
        },1000); 
       },15000); 
     }); 

但股利。

回答

1

你只是延缓在一起,这就是为什么他们仍然一起运行。你想要的是将它们从延迟

$('#monitor').click(function(){ 

    //a jQuery object is like an array 
    var checked = $('#status_table tr [id^="monitor_"]:checked'); 

    (function loop(i){ 

    //monitor element at index i 
    monitoring($(checked[i]).parent('tr')); 

    //delay 
    setTimeout(function(){ 
     //when incremented i is less than the number of rows, call loop for next index 
     if(++i<checked.length) loop(i); 
    },15000); 

    }(0)); //start with 0 

}); 
+0

谢谢!它的工作原理,但我需要循环它。我可以问什么是(0); //从0开始? – yvonnezoe 2013-05-03 08:39:15

+0

我使用setInterval创建了另一个循环。但是当行数减少时(表格是动态的),它会继续找到那些最初的行并且乱七八糟。 – yvonnezoe 2013-05-03 09:07:15

+1

@yvonnezoe'loop'是一个函数,'(0)'立即用参数'0'调用它。这就像调用定义'loop'并一次调用它。 15秒后,它再次调用自己,现在使用1,直到使用'checked'中的所有值。我使用'setTimeout'而不是设置更简洁控制的时间间隔。 – Joseph 2013-05-03 10:01:53

0

试试这个:

setTimeout(function(){ 
    monitoring($(this).closest('tr')); 
},1000); 
+0

啊是的,这是一个错字。我想编辑我的问题,但是stackoverflow刚刚超载。 – yvonnezoe 2013-05-03 08:36:45

2

替换您如下一行:

monitoring($(this).parents('tr')); 

这一个:

monitoring($(this).parent('tr')); 
+0

,给了我undefined undefined undefined而不是fbType,fbNum和eachStatus。 – yvonnezoe 2013-05-03 08:36:10