Skip to content

Instantly share code, notes, and snippets.

@johnpc
Last active March 7, 2022 17:03
Show Gist options
  • Save johnpc/ad134c65b939f12f1112b004782b9075 to your computer and use it in GitHub Desktop.
Save johnpc/ad134c65b939f12f1112b004782b9075 to your computer and use it in GitHub Desktop.
react-exec-and-stop
import {useState} from "react";
window.shouldStopCode = false;
function App() {
// move(); move();
const [workingCode, setWorkingCode] = useState("");
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const move = async () => {
console.log(`Moving at ${Date.now()}`);
await sleep(1000);
};
const runCode = (code) => {
eval(
`const fun = async() => {${code.replaceAll(
"move()",
"console.log(window.shouldStopCode); if (window.shouldStopCode) { throw new Error('CODE STOPPED')} await move()"
)}}; fun();`
);
};
const stopCode = () => {
window.shouldStopCode = true;
setTimeout(() => window.shouldStopCode = false, 2000);
};
return (
<div className="App">
<input onChange={(e) => setWorkingCode(e.target.value)}></input>
<button onClick={() => runCode(workingCode)}>Run Code</button>
<button onClick={() => stopCode()}>Stop Code</button>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment