0

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?

Jon Behnken
  • 560
  • 1
  • 3
  • 14
  • 1
    You could just check for an error in `check_progress` and return before `setTimeout` is used to queue up another call to the `worker` – gabriel.hayes Oct 31 '19 at 16:38
  • @user1538301 wow can't believe I missed that -- worked like a charm. Thank you. – Jon Behnken Oct 31 '19 at 16:48
  • Why was this question downvoted? I understand the solution was fairly simple but I hardly think the effort and content of this question is worthy of a downvote? – Jon Behnken Oct 31 '19 at 18:13
  • I'm not sure. I went ahead and gave it an upvote, but more than likely its because the actual solution was that you needed a break :) I'm sure if you ran for coffee and took a second look at it you'd have come up with a similar solution shortly after. – gabriel.hayes Oct 31 '19 at 18:57

0 Answers0