Running a string as a function in javascript setTimeout?

Why does this code work?

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

Must not be?

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

How to setTimeout convert a string to a function?

+5
source share
3 answers

Quote MDN documentation setTimeout

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

As suggested by MDN, it is best to avoid strings in setTimeout , since an implementation can eval pass a string.


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 ] ) 

Sets the timeout to compile and run code after timeouts in milliseconds.

+6
source

docs for firefox , IE

Intended behavior: you can pass a pointer to a function or string as the first argument.

Regarding this, JS is a scripting language, so string evaluation for some interpreted code (e.g. eval does) is what it is very good at.

edit: I meant "very good" in the context of the fact that it is a scripting language used to parse strings for working code, as Jimbo Jonny points out; this can be avoided.

+2
source

Basically, the specification allows it to go anyway, so browsers will use it anyway. It's simple.

Not recommended because it uses eval in the string. A functional path is the best way.

+1
source

Source: https://habr.com/ru/post/1241148/


All Articles