karlkoder-playground/js/code-runner.js

42 lines
914 B
JavaScript

export class CodeRunner {
constructor(cons) {
this.console = cons;
this.isRunning = false;
}
setCode(code) {
this.code = code;
}
async run() {
this.isRunning = true;
this.console.log("Running code...");
// Stored globally so lib.js can access it
globalThis.libInternalAbortController = new AbortController();
// Use RNG to prevent caching
const encodedText = encodeURIComponent(
this.code + `/*(tph): ${Math.random()}*/`,
);
try {
await import(`data:text/javascript;charset=utf-8,${encodedText}`);
} catch (error) {
this.console.log(error);
}
}
stop() {
this.isRunning = false;
globalThis.libInternalAbortController?.abort();
}
toggle() {
if (this.isRunning) this.stop();
else this.run();
}
}