repeat function until true
javascript
Solution
`getUserData` calls an asynchronous function internally, so it has returned long before the AJAX call is actually finished.
Instead of doing this in a setInterval loop, you might want to try calling `getUserData` again in the failure case. For example:
function getUserData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
if (resp.status) {
alert("true");
} else {
setTimeout(getUserData, 10000);
}
}
}
xhr.send();
}
getUserData();
Problem
I am trying call an ajax request until it returns a true value. I have tried the following code but it does not return any results and no errors in the console. Any idea what I am doing wrong? ``` function getUserData() { var xhr = new XMLHttpRequest(); xhr.open("GET", "http://api.example.com/data.json", true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var resp = JSON.parse(xhr.responseText); return resp.status; } } xhr.send(); } setInterval(function () { if (getUserData() === "true") { alert("true"); } }, 10000); ```