Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout and V8

Tags:

javascript

v8

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?

like image 700
ren Avatar asked Sep 08 '12 23:09

ren


People also ask

Is setTimeout part of V8?

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.

Does setTimeout block event loop?

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.

Does setTimeout stop execution?

No, setTimeout does not pause execution of other code.

Is setTimeout deprecated?

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);


1 Answers

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...)

like image 68
T.J. Crowder Avatar answered Oct 23 '22 12:10

T.J. Crowder