Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Leak with an XMLHttpRequest and setInterval

Here's some code that I run on Google Chrome 19.0.1061.1 (Official Build 125213) dev:

<html>
<title>Memory Leak</title>
<script type="text/javascript">
    (function(){
        this.window.setInterval(function() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '', false);
            xhr.send();
        }, 50);
    }).call(this);
</script>
</html>

When I inspect memory usage in chrome://tasks, I can see that "Private Memory" is growing up indefinitely (8GB RAM config). If I change the sample of code above to something like that:

<html>
<title>Memory Leak</title>
<script type="text/javascript">
    (function(){
        var xhr = new XMLHttpRequest();
        var timeout = this.window.setInterval(function() {
            xhr.open('GET', '', false);
            xhr.send();
        }, 50);
    }).call(this);
</script>
</html>

It's now OK.

I don't get it. Why keeping a reference to the setInterval function helps and why defining only one xhr helps since previous declaration was in a closure? Is it related only to v8?

I would appreciate your insights on it.

like image 478
François Beaufort Avatar asked Jan 18 '23 03:01

François Beaufort


2 Answers

In the first one, you're instantiating a new XMLHttpRequest object on each call to the iterator function. The request objects will stick around at least until the HTTP requests complete. Initiating 200 HTTP requests per second is going to clog the browser up something fierce, since it won't actually perform all the requests; there's a limit to how many concurrent connections it'll open.

like image 200
Pointy Avatar answered Jan 20 '23 14:01

Pointy


How long does this http call take? if this takes longer then 50ms (which is a very shot amount of time) then the first case will be creating more and more pending requests while then second case you are reusing the same XMLHttpRequest which may have the effect of canceling the previous call.

like image 45
David Waters Avatar answered Jan 20 '23 16:01

David Waters