2

I've got next code that fills page with data I get from server every 10 sec:

var refreshFunction = function() {
        //get data from server
        $.get("<c:out value="${baseURL}"/>/js/getCounts", function(data) {
            vardata = data;
        });

        if (vardata != null) {
            //divide
            countArray = vardata.split("/");
            //if server returns "-" or new array with new structure
            if ((vardata == "-" || length != countArray.length)
                    && !(document.getElementById('requestForm') instanceof Object)) {
                //reload
                location.reload();
                clearInterval(refreshId);
            } else {

                //fill page with data
                for (var j = 0; j <= countArray.length; j++) {
                    console.log(countArray[j]);
                    $('#badge_' + (j + 1)).text(countArray[j]);
                }

            }
        }

    };

    $(document).ready(function() {
        refreshId = setInterval(refreshFunction, 10000);
    });

The code works, but if I open application and then turn off my server, script will never stop. I'm having

Failed to load resource: net::ERR_CONNECTION_REFUSED

How can I catch it and stop the script after that? I was trying to wrap code blocks with try and catch(e), but doesn't help.

1 Answer 1

2

Since the AJAX request is executed asynchronously, wrapping your code in try ... catch will not catch the exception. The exception happens after your code has finished executing.

You should handle the .fail case on the object returned by $.get to avoid seeing that error reported on the console:

 var jqxhr = $.get("<c:out value="${baseURL}"/>/js/getCounts", function() {
    vardata = data;
  })
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

As a side note, you should put the complete body of your function inside the call back in $.get. Otherwise, you'll always be running your code with the old dataset, not the new one.

This problem doesn't show up in your code in the first execution because vardata is probably undefined and in Javascript land, undefined != null is false.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.