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?
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.
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.
The eval() function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With