VM:setTimeout在浏览器vm.runInNewContext中不起作用

时间:2019-04-19 18:25:45

标签: javascript node.js google-chrome v8 node-vm2

我正在使用vm模块在浏览器中执行JS脚本,如下所示。

vm.runInNewContext(codeToEval, sandboxObject);

setTimeout,setInterval和其他内置的间隔方法不起作用,即使我在使用vm.createContext({setTimeout})创建的sandboxObject中公开它们也是如此。

console.log('start');
setTimeout(()=> {
     console.log('hello timeout');
 }, 2000);

 console.log('end');

输出:

start
end

要注意的是,当我添加.bind(this)时,超时工作并在该行中断,说.bind不是函数。

console.log('start');
setTimeout(()=> {
     console.log('hello timeout');
 }, 2000).bind(this);

 console.log('end');

输出:

start
hello timeout
// and an error in console saying setTimeout(...).bind is not a function
// and end is not printed

Chrome 70

平台Ubuntu 18.04

V8

0 个答案:

没有答案