+ 1
How to execute x without any error?
I know this code will give an error because of the priority. How can I run this code without an error and print x as 1. Can I make it happen using async? Code: setTimeout(()=>{var x = 1}, 0) console.log(x) https://code.sololearn.com/Wi4H6GO6B2g4/?ref=app
7 ответов
+ 3
You could wrap setInterval method in a promise object and log whatever the promise resolves.
https://code.sololearn.com/WA3ei7JfzuWS
+ 3
Alex
Yes, but I just didn't see the point of setting a zero ms timeout. I mean, if we want no delay, then why set a timeout, why not just execute the block immediately👌
+ 2
Variable <x> is defined in a block (arrow function body) how could you expect it to exist outside that arrow function body scope?
Also, what's the point of the zero ms timeout?
It might just work if you instead define <x> at global scope or any scope outside the arrow function body. The arrow function only assigns value 1 to <x>.
But even with that, you'd still have to also set a timeout for the time when <x> will be logged in console. Otherwise, <x> will most likely still have its original value.
+ 1
Sorry, I just don't know how that was possible. Hope someone who knows this better can help you out soon.
+ 1
Ipang setTimeout with a 0 ms timeout will put the callback function on the callstack of the event loop. The effect of it is that all synchronous code will execute first (blocking the event loop). The event loop will then eventually (pun intended) pick it up and execute it.
(Of course it's explained in a nutshell. Event loops are of course a bit more complex)
0
Settimeout is an web api and it's consider as a asynchronous function. So the "console.log" will execute first. I wanna know if there is any way to make wait the "console.log(x)" After the execution of settimeout. Ipang
0
let func = () => { var x = 1; console.log(x)};
setTimeout(func, 0)
I think it will work in like this or like this
let t = setTimeout(()=>{var x = 1}, 0)
console.log(t)