Long Polling - Problems with Internet Explorer 8
Asked Answered
H

1

7

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.

Horta answered 6/2, 2012 at 23:57 Comment(3)
The first line should be function longPollRequest() { instead. Is that just a typo in your post?Lenee
I bet IE8 caches your request: Have your tried `url: '/test-path?nocache='+(Math.random*900000+100000).toString()Stellate
@Jocob Ya that was just a typo. Fixed.Horta
P
10

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.

Pontus answered 7/2, 2012 at 0:8 Comment(1)
Awesome, your solution works. Thanks for pointing me in the right direction. I ended up specifying the Cache-Control: no-cache response header for all long-polling responses and it is working as well.Horta

© 2022 - 2024 — McMap. All rights reserved.