I have an AJAX function I'd like to kill, but it is outside of the function. Take a look:
function waitForMsg(){
var heartbeat = $.ajax({
type: "GET",
url: "includes/push_events.php",
tryCount : 0,
retryLimit : 3,
async: true,
cache: false,
// timeout: 500,
success: function(data){
console.log(data);
if(data){
if(data.current_date_time){
updateTime(data.current_date_time);
}
if(data.color){
console.log("Receiving data");
displayAlert(data.color, data.notification_message, data.sound, data.title);
}
if(data.user_disabled){
console.log("Receiving data");
fastLogoff();
checkDisabled();
}
}
setTimeout(
waitForMsg,
5000
);
},
error: function(data){
if (data.status == 500) {
console.log("Connection Lost to Server (500)");
$.ajax(this);
} else {
console.log("Unknown Error. (Reload)");
$.ajax(this);
}
},
dataType: "json"
});
};
// Detect browser open.
$(document).ready(function(){
// window.onunload = function(){alert('closing')};
// mainmode();
$('#alertbox').click(function(){
$('#alertbox').slideUp("slow");
});
$(document).ready(function(){
$('#alertbox').click(function(){
$('#alertbox').slideUp("slow");
});
// Check focal point
var window_focus = true;
$(window).focus(function() {
window_focus = true;
console.log('Focus');
});
$(window).blur(function() {
window_focus = false;
console.log('Blur');
});
setInterval(function(){
if(window_focus == true){
console.log('in focus');
waitForMsg();
}else{
console.log('out of focus');
heartbeat.abort();
}
}, 5000);
});
});
If you notice, the ajax is outside of the document.ready. I am trying to kill the ajax calls if the user goes to a different window, then restart the calls once the return to the window. The start works, but if the user goes away from the window, it gives me the "heartbeat is not defined". Obviously this is because its outside of that function. Any work arounds?