5

Why does this code work?

setTimeout("document.body.innerHTML = 'TEST'", 1000)

Shouldn't it be?

setTimeout(function() {
    document.body.innerHTML = 'TEST'
}, 1000)

How does setTimeout convert string to function?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 3
    From [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout): *"code in the alternate syntax is **a string of code** you want to execute after delay milliseconds (using this syntax is not recommended for the same reasons as using `eval()`)"* – Josh Crozier Jan 21 '16 at 16:19
  • An interesting related view point [here](https://stackoverflow.com/q/3492015/465053). – RBT Oct 07 '17 at 09:20

3 Answers3

6

Quoting MDN's setTimeout documentation

code in the alternate syntax is a string of code you want to execute after delay milliseconds (using this syntax is not recommended for the same reasons as using eval())

As suggested in the MDN, it is better to avoid strings in the setTimeout as the implementation may eval the string passed.


This is not just a Browser implementation thing, but the HTML specification itself defines it this way in this section

handle = window . setTimeout( code [, timeout ] )

Schedules a timeout to compile and run code after timeout milliseconds.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

docs for firefox , IE

It's intended behaviour: you can pass a function pointer or a string as first argument.

As for how it does it, JS is a scripting language, so evaluating a string to some interpreted code (like eval does) is what it's very good at.

edit: I meant 'very good at' in the context of it being a scripting language, used to parse strings to working code, as Jimbo Jonny points out; it is something to be avoided.

Nikki Koole
  • 136
  • 1
  • 8
  • Actually, eval'ing a string to code is something that forces it to forego a bunch of otherwise beneficial optimizations, slowing down not only that line, but many other operations within the code. It is not something it's good at. It is actually something it is very poor at, and should be avoided where possible. – Jimbo Jonny Jan 21 '16 at 20:34
1

Basically the spec allows it to go either way, so the browsers will take it either way. That simple.

Not recommended though because it uses eval on the string. The function way is the better way.

Jimbo Jonny
  • 3,549
  • 1
  • 19
  • 23