Is Javascript "eval" Synchronous Or Asynchronous?
Consider the following code: eval('.....;a=5;b=10;'); eval('a+b'); If in case here the 1st eval runs for long time, will my next eval return an error mentioning as a and b are und
Solution 1:
eval
is synchronous in nature. But the evaluations/expressions inside the eval
may have asynchronous code like setTimeout
or setInterval
.
For an instance.
Method 1: (synchronous example)
eval('var a=5, b=10;');
eval('console.log(a+b)');
Method 2: (asynchronous example)
eval('setInterval(function(){window["a"]=5, window["b"]=10;}, 1000)');
eval('console.log(typeof a)');
Note: Anyways, it's not recommended to use eval
as mentioned in https://stackoverflow.com/a/86580/7055233
Solution 2:
eval
is synchronous.
Lets look at this example:
console.log("before")
eval("console.log('eval')");
console.log("after");
You can see in that the print is in the order.
if it was asynchronous for example in this case:
console.log("before");
setTimeout(()=>console.log("asynchronous"),0)
console.log("after")
The asynchronous run after.
Post a Comment for "Is Javascript "eval" Synchronous Or Asynchronous?"