I’m trying to stop my setInterval()
call. The best would be to identify whenever my AJAX request is fulfilled. So, If I got my AJAX GET response, then clearinterval()
.
$(document).on('submit', '#post-form', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/send',
data: {
room_name: $('#room_name').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
//alert(data)
}
});
$(document).ready(function com() {
loop = setInterval(function() {
$.ajax({
type: 'GET',
url: "/trafic",
success: function check(response) {
//SOME CODE//
},
error: function(response) {
//SOME CODE//
}
});
}, 1000)
setTimeout(clearInterval(loop), 10000);
})
});
I tried to set a timeout, but it is very imprecise as it may take longer/shorter than the delay. So I would need something like if GET successful {clear interval()}
2
Answers
You need to move the
clearInterval()
call into thesuccess
callback of the AJAX call. You’ll also need to move theloop
interval higher up in your code so that it can be referenced from thesuccess
callback.I’m also not sure why the
loop
interval is wrapped in a$(document).ready()
call, because you can be assured that the document is ready if it is submitted. Also, the variableloop
is awfully ambiguous. Try using the name of the API endpoint instead, liketraffic
.Try this code:
Can I ask you first why did you use setInterval on this HTTP request ? You are probably using more computation power than you need.
You should probably make the request async (e.g https://petetasker.com/using-async-await-jquerys-ajax)
If you want to wait for an event to appear, you may want to have a look at web sockets (https://www.tutorialspoint.com/websockets/index.htm)