I have a simple ajax request to load more posts. I am thinking about using locks when one "load more" ajax request is called to prevent calling "load more" multiple times. The plan is to lock the ajax request method when it is called and release the lock when it returns with request.done or request.fail methods. Is there any case when the jQuery ajax request doesn't call either of those methods (e.g. brief loss of Internet connection)?
1 Answers
Beneath all the wrappers, jQuery's ajax is simply an XMLHttpRequest. An XMLHttpRequest can be in one of the following states:
UNSENT
(numeric value 0): The object has been constructed.OPENED
(numeric value 1): The open() method has been successfully invoked and the request can be made using the send() method.HEADERS_RECEIVED
(numeric value 2): All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.LOADING
(numeric value 3): The response entity body is being received.DONE
(numeric value 4): The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).
Essentially you're asking if there's a case when DONE
is never reached after the request is OPENED
.
If there are infinite redirects we'll jump from HEADERS_RECEIVED
to DONE
(with a failing status) and the request is complete.
If redirects succeed, we continue to LOADING
, which will then continue to DONE
if the data was received successfully.
However, what if data is never received and we're left waiting? XMLHttpRequest has a property timeout
which specifies after how many milliseconds to fail the request as it timed out. According to this question, however, jQuery doesn't provide a default non-null value for it (I haven't checked it myself, the answer may be outdated, you'll have to reference the latest source for that). Some browsers have built-in defaults for timeouts, but they vary from vendor to vendor.
Therefore, if you don't manually configure a timeout, it's possible, though unlikely, that the request is left hanging indefinitely. As such, it would be wise to implement a failsafe timeout.