gpt4 book ai didi

javascript - clearInterval 并将变量设置为 null 不起作用

转载 作者:行者123 更新时间:2023-12-02 14:22:08 25 4
gpt4 key购买 nike

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

<script>

supportchatinterval = 5000;

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

function checkForChangesSupport() {
$.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");
supportchatinterval = null;
clearInterval(supportchatinterval);
};

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

</script>

最佳答案

没有需要清除的间隔,因为每次 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>

关于javascript - clearInterval 并将变量设置为 null 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38575842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com