0

I have the following jQuery code that fetches a html page that I generate every second. After a while, it leads to an out of memory error. How to fix?

    $(document).ready(function() {
        setInterval(function() {
            $.get('some_page.html', function (data) {
                $('#some_div').html(data);
            });
        }, 1000);
    });
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • why not refresh the page rather than `get` every second plus every second is a bit much, why not make it refresh every 10? – Deckerz Sep 11 '17 at 10:54
  • Because making an AJAX call every second is going to be extremely heavy on both the browser and the server. – G.Hunt Sep 11 '17 at 10:54
  • Inspect this in Network tab of browser dev tools. Most likely what is happening the new requests are being fired before the previous event finished and that causes memory and bandwith problems after a while. You should make sure the previous request has finished before calling again – Jarek.D Sep 11 '17 at 11:15

1 Answers1

0

If what is happening is the new requests are being fired before the previous event finished, make sure the previous request has finished before calling again. I haven't really tested the code below but it should point you in the right direction. Use setTimeout and recursion instead of setInterval. Obviously this solution doesn't give you sharp one second intervals if for some reason they are required (more like one second plus the request cycle that is down to network conditions of the user) but I assume you just need a face paced refresh and strict timing is not crucial.

Still I second the comments above, that 1 second http request interval is risky and a bit abusive to both browser and server, and so there should be a really good reason to use it.

$(document).ready(function() {
    function refresh(){
       $.get('some_page.html', function (data) {
            $('#some_div').html(data);

            // call itself recursively
            setTimeout(refresh, 1000);
        });            
    };

    // init
    refresh();
});
Jarek.D
  • 1,274
  • 1
  • 8
  • 18