The js code will continue to run even if the element is removed from the page.
The first difficulty when coding with react-js
. Because the page is not reloaded, the initial scripts are still running, such as setInterval, websocket, etc
code. The simple example below has the elements removed but is still running. Doesn't work if I have to create using global variables
<button onclick="createNewJsCode()">create new js</button> <button onclick="removeJsCode()">remove js</button> <script> let id = '' function createNewJsCode(){ let s = document.createElement('script') let code = 'setInterval(`console.log(new Date())`,500)' s.id = (id = crypto.randomUUID()) s.appendChild(document.createTextNode(code)); document.body.appendChild(s); } function removeJsCode(){ document.getElementById(id).remove() } </script>
You can't just delete the
<script>
node, you have to do some more specific cleanup.setInterval
Returns an interval ID that you can pass toclearInterval
to stop it.Generally speaking, I'd say your code doesn't make much sense in a React context, but in your case you can do this:
This is a React question, here is an example of using
setInterval
in a React component. If you use some form of React Router, the code below will also uninstall/install etc correctly.