I have a function that performs an AJAX GET request every 1 second to retrieve data and update a progress bar. I'm using setTimeout
to accomplish this. Here is the code:
function check_progress(thread_id) {
function worker() {
$.get('ecab_run/progress/' + thread_id, function(data) {
progress = data['progress'];
status_message = data['status_message'];
if (progress < 100) {
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$('.progress-bar')[0].innerHTML = progress+"%";
$('#status-message')[0].innerHTML = status_message
timer = setTimeout(worker, 1000);
// console.log(timer);
} else if ( progress == 100 ){
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$('.progress-bar')[0].innerHTML = progress+"%";
}
})
return status_message;
}
worker();
}
The function is called after a successful POST as such:
$('#ecab-run-dates').submit(function(e){
e.preventDefault();
var formData = $('form').serialize();
$.ajax({
url:'',
type:'post',
data:formData,
success:function(data){
thread_id = data;
$('.progress-container').show();
check_progress(thread_id);
}
});
});
The backend returns status messages as the behind-the-scenes functions execute, and when it encounters an error, it returns Error: could not compile data
or something similar.
My initial thought was to use the error message as a condition for stopping the check_progress
function. I've read several answers, including this one that say to use clearTimeout
, but I'm not exactly sure how to structure that in my code. Can someone help me exit the setTimeout
loop when encountering an error?