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?
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?
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.
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.
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.