如何在setInterval循环中设置延迟

How to set delay in a setInterval loop?

本文关键字:设置 延迟 循环 setInterval      更新时间:2023-09-26

这是我的部分代码:

$('#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");
                }
            });
        }

我怎样才能延迟每一行的函数调用?我尝试了以下命令

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

但是div #ptest显示的是undefined

替换以下行:

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

:

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

你只是在拖延他们在一起,这就是为什么他们还在一起跑。你想要的是延迟它们彼此

$('#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
});

试试这个:

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