clearInterval和设置变量为null无效

时间:2016-07-25 19:21:18

标签: javascript jquery

尽管我的代码中有in_time_zone AND supportchatinterval = null;(请参阅clearInterval(supportchatinterval);onBlur()),但每5000毫秒该函数仍然在相同的setInterval中加载getTableSupport.php(参见onFocus()。当设置onBlur函数时,我想停止setInterval直到再次调用checkForChangesSupport()

onFocus

3 个答案:

答案 0 :(得分:1)

没有要清除的间隔,因为每次checkForChangesSupport()运行时都会创建新的超时。无论哪种方式,supportchatinterval只是一个整数,并且无法清除"。

要停止此操作,您可以引入一个标志并检查该功能是否应该运行。此外,您应该致电checkForChangesSupport()再次启动计时器。

<script>

supportchatinterval = 5000;
var flag = 1;

$(document).ready(function(){
    checkForChangesSupport();
    setTimeout(checkForChangesSupport, supportchatinterval);
});

function checkForChangesSupport() {
   if(flag){
      $.get("getCountSupport.php", function(response) {
         if(response == 1) {
            refreshTableSupport();
         }
         setTimeout(checkForChangesSupport, supportchatinterval)
      });
   }
}

function refreshTableSupport(){
    $('#tableHolderSupport').load('getTableSupport.php');
}

</script>

<script type="text/javascript">

function onBlur(){
document.body.className = 'blurred';
$.get("afk.php?afk=1");
flag = 0;
};

function onFocus() {
document.body.className = 'focused';
$.get("afk.php?afk=0");
flag = 1;
checkForChangesSupport();
}

</script>

答案 1 :(得分:1)

在您的情况下,

supportchatinterval与当前正在运行的超时无关。所有这些都是代码运行的时间。您需要做的是存储生成的实际超时ID。

theTimeout = setTimeout(checkForChangesSupport, supportchatinterval);

你使用那个

window.clearTimeout(theTimeout);

答案 2 :(得分:0)

我建议你使用setInterval,这更适合你的用例。

然后,在模糊时你可以清除它。

您的主要问题是间隔的延迟(作为参数给出)与其设置时返回的句柄之间的混淆,然后用作一个参数os clearInterval取消它。

代码:

    // This is a delay between function calls, in milliseconds
    supportchatinterval = 5000;
    // This will be the handle returned by setInterval, which be usefull to cancel 
    // it later
    intervalid = null;

    $(document).ready(function(){
        checkForChangesSupport();
        intervalid = setInterval(checkForChangesSupport, supportchatinterval);
    });

    function checkForChangesSupport() {
        $.get("getCountSupport.php", function(response) {
            if (response == 1) {
               refreshTableSupport();
            }
        });
    }

    function refreshTableSupport(){
        $('#tableHolderSupport').load('getTableSupport.php');
    }

    function onBlur(){
        document.body.className = 'blurred';
        $.get("afk.php?afk=1");
        clearInterval(intervalid);
    };

    function onFocus() {
        document.body.className = 'focused';
        $.get("afk.php?afk=0");
        refreshTableSupport();
    }

如果您不仅要停止在模糊时调用间隔函数,而且还有结果存在时,只需在那里调用clearInterval

    function checkForChangesSupport() {
        $.get("getCountSupport.php", function(response) {
            if (response == 1) {
               refreshTableSupport();
               clearInterval(intervalid);
            }
        });
    }