我正在使用浏览器中的 vm 模块执行 JS 脚本,如下所示。
vm.runInNewContext(codeToEval, sandboxObject);
setTimeout、setInterval 和其他内置方法的间隔不起作用,即使我在使用创建的 sandboxObject 中公开它们vm.createContext({setTimeout})
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
铬 70
平台 Ubuntu 18.04
V8