michelle michelle - 4 months ago 17
jQuery Question

clearInterval and setting variable to null not working

Despite having

supportchatinterval = null;
AND
clearInterval(supportchatinterval);
in my code below (see
onBlur()
and
onFocus()
) every 5000ms the function is still loading getTableSupport.php at the same setInterval (see
checkForChangesSupport()
. When the function onBlur is set I want to stop the setInterval until
onFocus
is called again.



<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>

Answer

There's no interval to clear, since the new timeout is created each time checkForChangesSupport() runs. Either way, supportchatinterval is just an integer and can't be "cleared".

To stop that, you could just nullify the function. Replace this

supportchatinterval = null;
clearInterval(supportchatinterval);

with this:

checkForChangesSupport = null;