Reputation: 117
I have a script that sends ajax request in intervals and ideally it should never cease to work.
<script type="text/javascript">
var delay = 750;
window.setInterval(endlessJob, delay);
function endlessJob() {
//read from endless steam of data
var data = getData();
sendAjax(data);
}
function sendAjax(data) {
$.ajax({
url: "url",
jsonp: "jsonp",
dataType: "jsonp",
data: {
q: data
},
success: function (res) {
doSomething();
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('ajax error! ' + errorThrown.message + "\n status: " + textStatus);
//should resume endless job, but the script fails with error(((((((((((
window.setInterval(endlessJob, delay);
}
});
}
</script>
And then there's the problem: after a number of requests, ussually it's between 1000 and 2000, the request fails with Internal Server Error 500 and the function never resumes. Have already tried try/catch, but with no success(. Basically i need to just swallow the error and continue the script. Can someone assist me please?
Upvotes: 1
Views: 1528
Reputation: 2855
You are making a call to the server every 3/4 of a second over a thousand times. Eventually you will have calls being made before the previous call has had enough time to complete. If you want your script to run for a very long time i recommend you either extend your delay to say maybe 1500-2000 (1.5-2 seconds depending on your server) or change your code to require a callback. This way the next call won't be initialized until the previous one has been completed. Here is your code modified with a callback. I did not have time to test it but hopefully it will give you a general idea of how to write it with callbacks.
<script>
function start() {
var data = getData();
sendAjax(data, function(callbackText) {
console.log(callbackText);
start(); // the previous ajax call is done. we may now start the next one
});
}
function sendAjax(data, callback) {
$.ajax({
url: "url",
jsonp: "jsonp",
dataType: "jsonp",
data: {
q: data
},
success: function(res) {
doSomething();
callback("This call is done. Now moving on to the next one.");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ajax error! ' + errorThrown.message + "\n status: " + textStatus);
//should resume endless job, but the script fails with error(((((((((((
window.setInterval(endlessJob, delay);
}
});
}
start(); // start the entire process
</script>
Upvotes: 2