2

Possible Duplicate:
Is there ever a good reason to pass a string to setTimeout?

I just read a comment stating it is bad practice.. Is that so? And why?

Community
  • 1
  • 1
TweeZz
  • 4,779
  • 5
  • 39
  • 53
  • It is bad practice because it uses an implied `eval()` which is a security risk. – g.d.d.c Jun 03 '11 at 20:56
  • Are you talkin' about my comment? :) – Chris Baker Jun 03 '11 at 20:57
  • It's a ticking time-bomb of error on line 1 – generalhenry Jun 03 '11 at 20:59
  • @Chris: yea :) [this one](http://stackoverflow.com/questions/6232383/little-help-with-javascript-code-involving-settimeout-method/6232402#comment-7262186).. Sorry for the duplicate :| – TweeZz Jun 03 '11 at 21:02
  • The thing is that I don't remember having any issues with it? – TweeZz Jun 03 '11 at 21:04
  • 2
    The thing is... this used to be how you did it. "Back in the day", all you could do was throw strings around and eval them. As the language matured, this pattern became obsolete. But, similar to the entire history of the Internet Explorer browser, things have been left ambiguous in the name of backward compatibility and legacy support. So, you still can - but shouldn't. And there might still be some rare occasion where this is still useful. That occasion will be so rare and complex that you and I probably wouldn't recognize the occasion when it occurs- there's always another way. :) – Chris Baker Jun 03 '11 at 21:09

2 Answers2

4

Yes, it is.

The string must be eval'd, which is evil (and very slow).
It also prevents you from using local variables in the callback.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 'It also prevents you from using local variables in the callback' Could you pls elaborate a bit on that? – TweeZz Jun 03 '11 at 21:06
  • The callback can't use locals from the code that called `setTimeout` (unlike a function expression) – SLaks Jun 03 '11 at 21:55
2

It's a bad practice for the same reason that using eval is bad. You're executing strings as code. This has both performance and security penalties.

Yuliy
  • 17,381
  • 6
  • 41
  • 47