Memory leak for javascript setInterval

Is there a difference between the two statements

setInterval(animateImage, 1000);

or 

setInterval('animateImage()', 1000);

Whether the second statement will be interpreted by the js browser engine in any other way that might cause memory leak or performance problems. The same thing happens with the challenge setTimeout(). The application uses 4 timer calls with an interval of 1-2 seconds.

+3
source share
5 answers

The biggest difference is that the second operator invokes a animateImage()global estimate .

This can lead to problems if

  • animateImage not located in a global area
  • animateImage must access variables that are not in the global scope

eg. below will not be :

function foo() {
    var answer = 42;
    function bar() {
        alert(answer);
    }
    setTimeout('bar()', 1000);
}

foo();

, ;)

, , "", eval .

+6

. , eval'd, . - , , , .

, :

setInterval(function() {
    animateImage(...);
}, 1000);
+3

, , , . , eval.

+2

I do not think so. You want to use callbacks to avoid memory leaks.

0
source

I recommend using it like this:

setInterval(function(param1, param2){animateImage(param1, param2)}, 1000);

pass parameters, not pass them at the end

0
source

All Articles