如何将setInterval周期设置为变量并删除等待时间?

时间:2013-05-07 04:12:29

标签: javascript jquery

我的每一行都有一个带复选框的表格。选中复选框后,函数将循环以更新每行的状态。

这是我的工作小提琴:http://jsfiddle.net/qJdaA/2/ 我使用setInterval()来循环该函数。由于表是动态的,我不知道列表将持续多长时间。所以我将句点设置为变量index*4000,如下所示:

$('#monitor').click(function () {
    $('#monitor').attr('disabled','true');
    bigloop=setInterval(function () {
    var checked = $('#status_table tr [id^="monitor_"]:checked');
        if (checked.index()==-1){
            $('#monitor').attr('disabled','true');

        }else{
    (function loop(i) {
    $('#monitor').removeAttr('disabled');
        //monitor element at index i
        monitoring($(checked[i]).parents('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);
        }, 3000);

    }(0)); //start with 0

    }

}, index*4000);

然而,问题是它会等待第一个循环结束而不做任何事情。假设我在列表中有10个项目,那么在执行任务之前它会等待40秒。我该如何消除这个问题?

然后,如果在10个项目中,只检查了1行,我必须等待40秒才更新那一行,这是低效的。

我尝试设置var clength = checked.length并使用它与4000相乘。但它不起作用。为什么以及如何做?

1 个答案:

答案 0 :(得分:0)

如何删除间隔

的示例
<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
  // do things here
}
function myStopFunction()
{
// clear interval here
clearInterval(myVar);
}
</script>

或者

<script>
    var myVar=setInterval(myTimer,1000);
    function myTimer()
    {
      // do things here
    }
    function myStopFunction()
    {
    // clear interval here
    clearInterval(myVar);
    }
    </script>