mdrndv mdrndv - 4 months ago 11
Ajax Question

Request URL until required data arrives

What is the best way to periodically request URL and cancel requests when required data is present in the response in plain Javascript?

Say, I am requesting

posts
URI that returns JSON and want to cancel requests when
numberOfPosts
attribute in response is equal than some
N
.

Thanks!

Answer

Combine setInterval() with your web service call and cancel the interval once you got the expected response via clearInterval().

MDN about setInterval():

Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. Returns an intervalID.