You've claimed that the code does "come in the 'if'", so I assume the clearInterval
call is actually being made.
Given that, the most likely explanation is that the interval is being cleared (after all, select
isn't broken), but before the first "true"
response, you've already made more than one ajax call, and the other ones you're seeing are ones scheduled before the interval was cleared.
E.g., your code runs and:
- Fires off ajax call #1, which takes more than a second to complete
- Fires off ajax call #2
- Ajax call #1 completes but isn't
"true"
- Fires off ajax call #3
- Ajax call #2 completes and is
"true"
, clearing the interval
- Ajax call #3 completes
Mixing two separate asynchronous intervals (one via setInterval
and one via ajax
) is asking for trouble.
If the goal is to make the request once a second and stop when you get back "true"
, I would have the success handler schedule the next call, e.g.:
(function() {
var time = 0;
var started = 0;
start();
function start() {
started = Date.now();
$.ajax({
url: '...'
type: "POST",
dataType: "",
success: function(response) {
if (response != "true") {
// Schedule the next call to occur one second after we
// started the previous call; or almost immediately if
// the call took more than a second to complete
setTimeout(start, Math.max(0, 1000 - (Date.now() - started)));
}
time = time + 1000;
},
error: function() {
alert("FAIL");
}
});
}
})();