2025-10-10 18:01:02 +02:00

45 lines
947 B
JavaScript

export class CodeRunner {
constructor(console, codeStopper) {
this.console = console;
this.codeStopper = codeStopper;
this.isRunning = false;
}
setCode(code) {
this.code = code;
}
async run() {
this.isRunning = true;
this.console.log("Running code...");
this.codeStopper.start();
// 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;
this.codeStopper.stop();
this.console.log("Stopping code...");
}
toggle() {
if (this.isRunning) {
this.stop();
} else {
this.run();
}
}
}