Last active
March 7, 2022 17:03
-
-
Save johnpc/ad134c65b939f12f1112b004782b9075 to your computer and use it in GitHub Desktop.
react-exec-and-stop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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