3

Is there any difference between these 2 statements

setInterval(animateImage, 1000);
or 
setInterval('animateImage()', 1000);

Will the second statement be interpreted by the browser js engine is any different way that could cause memory leak or performance issues. Same is the case with the setTimeout() call. The application makes use of 4 timer calls with 1-2 sec intervals.

asked Apr 11, 2011 at 12:26

5 Answers 5

6

The biggest difference is that the second statement will cause animateImage() to be evaluated in global scope.

This can lead to problems if

  • animateImage is not in global scope
  • animateImage has to access variables that are not in global scope

E.g. the following will not work:

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

Actually there is never a reason to use the second statement, so the question about memory leaks is not relevant anymore ;)

And obviously, passing a direct reference to a function will be 'faster' than evaluating a string.

answered Apr 11, 2011 at 12:44
Sign up to request clarification or add additional context in comments.

Comments

3

Use the first one. It makes debugging nicer since there's no eval'd code involved, it is faster and cleaner. Eval is evil and it's good to avoid it whenever possible.

In case you ever need to pass an argument, use the following code:

setInterval(function() {
 animateImage(...);
}, 1000);
answered Apr 11, 2011 at 12:42

Comments

2

The second statement will probably be slightly slower and use more memory, but it wouldn't be significant either way. You should Use the first one regardless, because it's generally best to avoid using eval.

answered Apr 11, 2011 at 12:41

Comments

0

I don't think so. You want to use callbacks to avoid memory leaks.

answered Apr 11, 2011 at 12:43

Comments

0

I recommend using it like so:

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

to pass parameters instead of passing them at the end

answered Sep 26, 2011 at 9:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.