I'm trying to implement long polling using Netty and jQuery.
I have it working correctly with Chrome and Firefox, but Internet Explorer 8 is causing me problems.
I'm executing the following code which sends a request to my server, waits until a response is received from the server and then sends another request.
function longPollRequest() {
$.ajax({
url: '/test-path',
type: 'GET',
success: function(data, textStatus, jqXHR) {
longPollRequest();
console.log('Received: ' + data);
}
});
}
However, in IE8 I'm running into an infinite loop, which is freezing the browser. The interesting part is that my server is only receiving the first request from IE. I'm really puzzled as to what is going on. If anyone has any ideas I would really appreciate the help.
Disable caching and see if that fixes your issue:
function longPollRequest () {
$.ajax({
url : '/test-path',
type : 'GET',
cache : false,
success : function(data, textStatus, jqXHR) {
longPollRequest();
console.log('Received: ' + data);
}
});
}
This will force jQuery to append a time-stamp to each request. If the response is cached then it will return very quickly and there's a good chance that's what's causing your infinite loop.
You could also force a minimum delay between AJAX requests:
let lastRequestTime = 0;
function longPollRequest () {
lastRequestTime = new Date().getTime();
$.ajax({
url : '/test-path',
type : 'GET',
cache : false,
success : function(data, textStatus, jqXHR) {
let delay = ((new Date().getTime()) - lastRequestTime);
if (delay > 1000) {
delay = 0;
} else {
delay = (1000 - delay);
}
setTimeout(longPollRequest, delay);
console.log('Received: ' + data);
}
});
}
This checks the current time against the time of the last AJAX request. If it's more than one second then just run the function again without a delay, otherwise make the code wait until a second has gone by between requests. There is probably a more elegant way of defining the delay
variable but the above code should get you started.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With