Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between eval and setTimeout execute string code

Tags:

javascript

I know that eval and setTimeout can both accept a string as the (1 st) parameter, and I know that I'd better not use this. I'm just curious why is there a difference:

!function() {
    var foo = 123;
    eval("alert(foo)");
}();

!function() {
    var foo = 123;
    setTimeout("alert(foo)", 0);
}();

the first would work, and the second will give an error: foo is not defined

How are they executed behind the scene?

like image 608
wong2 Avatar asked Jul 27 '12 08:07

wong2


People also ask

Does setTimeout execute immediately?

Next, you can pass the milliseconds parameter, which will be the amount of time JavaScript will wait before executing the code. If you omit the second parameter, then setTimeout() will immediately execute the passed function without waiting at all.

Does setTimeout stop execution?

Working with asynchronous functions setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.

What does eval () do in JavaScript?

The eval() function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script.

Why we should not use eval in JavaScript?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!


1 Answers

See the reference of setTimeout on MDN.

String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

In contrast, the string literal passed to eval() is executed in the context of the call to eval.

like image 60
Wolfram Avatar answered Sep 21 '22 18:09

Wolfram