I've installed V8 standalone and execute javascript code like this: ./d8 source.js
. When I use setTimeout I receive ReferenceError: setTimeout is not defined
. Is this how it's supposed to be? Is it possible to somehow include this function?
The answer is NOT V8 (or other VMs)!! While famously known as “JavaScript Timers”, functions like setTimeout and setInterval are not part of the ECMAScript specs or any JavaScript engine implementations.
Explanation: The for loop is a blocking statement, so while the setTimeout() is non-blocking. The loop creates 3 setTimeouts which go to the event loop and then to event queue.
No, setTimeout does not pause execution of other code.
We all know that passing a string to setTimeout (or setInterval ) is evil, because it is run in the global scope, has performance issues, is potentially insecure if you're injecting any parameters, etc. So doing this is definitely deprecated: setTimeout('doSomething(someVar)', 10000);
For what it's worth, V8 has its own setTimeout
now (~7.5 years later), in the shell it provides. But it only takes one parameter (the function to call) and schedules it to be called once the current job is completed, roughly as though you'd passed 0
as the second parameter to the more familiar form of setTiemout
provided by browsers and Node.js.
So given example.js
:
console.log("a");
setTimeout(() => {
console.log("c");
}, 5000);
console.log("b");
then
$ v8 example.js
outputs
a b c
...with no appreciable delay between b
and c
.
(That example uses the v8
command installed by jsvu, which is at least one way you run code directly in V8. I think d8
got subsumed...)
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