程序员小柯
给代码块加了运行按钮,读者填进一段死循环怎么办?从 Galley 的实现看 Worker、QuickJS 和执行预算各自负责什么,并用三个可运行的例子验证。
2026 年 11 月 13 日
while (true) {}// 错误示范:这段不会在两秒后自行结束
const timer = setTimeout(() => {
throw new Error("运行超时");
}, 2000);
new Function("while (true) {}")();
clearTimeout(timer);console.log(typeof document); // "undefined"
console.log(typeof fetch); // "function"Worker 里仍然有 fetch
import type { QuickJSWASMModule } from "quickjs-emscripten-core";
// 在 Worker 内调用;QuickJS 是已经加载好的 Wasm 模块。
// 这个简版只处理同步表达式,不注入 console、网络或定时器。
function runExpression(QuickJS: QuickJSWASMModule, code: string) {
const runtime = QuickJS.newRuntime();
runtime.setMemoryLimit(32 * 1024 * 1024);
runtime.setMaxStackSize(512 * 1024);
const deadline = performance.now() + 2000;
runtime.setInterruptHandler(() => performance.now() >= deadline);
const vm = runtime.newContext();
try {
const result = vm.evalCode(code, "example.js");
const handle = result.error ?? result.value;
try {
return result.error
? { ok: false, error: vm.dump(handle) }
: { ok: true, value: vm.dump(handle) };
} finally {
handle.dispose();
}
} finally {
vm.dispose();
runtime.dispose();
}
}用户不写死循环,写一万次 console.log,一样能制造麻烦。解释器跑完了,页面还要接收和展示那些输出。
Galley 最多保存 200 行、累计长度不超过 20000 的输出,超出后标记截断。这里的长度按 JavaScript 的 string.length 算,不是网络传输的字节数。这个限制管的是准备交给页面的日志量。
停止后的状态也要收拾。当前几个代码块共用一个 Worker,终止会结束其中未完成的请求,下次运行再创建一个。如果要改成互不影响的并行运行,这个共享方式就需要一起调整。
console.log([10, 2, 7].sort((a, b) => a - b));回到那个运行按钮
console.log("fetch:", typeof fetch);
console.log("document:", typeof document);
console.log("localStorage:", typeof localStorage);回到那个运行按钮
while (true) {}程序员小柯