Does JavaScript setInterval() method cause memory leak?

前端 未结 8 1658
Happy的楠姐
Happy的楠姐 2020-11-29 22:15

Currently developing a JavaScript based animation project.

I have noticed that, proper use of setInterval(), setTimeout() and even re

8条回答
  •  一整个雨季
    2020-11-29 22:34

    I wanted to respond to your comment about setInterval and flickering:

    I have noticed that, proper use of setInterval(), setTimeout() and even requestAnimationFrame allocates memory without my request, and causes frequent garbage collection calls. More GC calls = flickers :-(

    You might want to try replacing the setInterval call with a less evil self-invoking function based on setTimeout. Paul Irish mentions this in the talk called 10 things I learned from the jQuery source (video here, notes here see #2). What you do is replace your call to setInterval with a function that invokes itself indirectly through setTimeout after it completes the work it's supposed to do. To quote the talk:

    Many have argued that setInterval is an evil function. It keeps calling a function at specified intervals regardless of whether the function is finished or not.

    Using your example code above, you could update your init function from:

    function init() 
    {
        var ref = window.setInterval(function() { draw(); }, 50);
    }
    

    to:

    function init()
    {
         //init stuff
    
         //awesome code
         
         //start rendering
         drawLoop();
    }
    
    function drawLoop()
    {
       //do work
       draw();
    
       //queue more work
       setTimeout(drawLoop, 50);
    }
    

    This should help a bit because:

    1. draw() won't be called again by your rendering loop until it's completed
    2. as many of the above answers point out, all of the uninterrupted function calls from setInterval do put overhead on the browser.
    3. debugging is a bit easier as you're not interrupted by the continued firing of setInterval

    Hope this helps!

提交回复
热议问题