js code keeps running even if element is removed from page.
first difficulty when coding with react-js
. because the page is not reloaded so the initial script is still running, like setInterval,websocket,etc
code. simple example below element has been removed but still running. not effective if i have to create with global variable
<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>
2
Answers
You can’t just remove the
<script>
node, you have to do a little more specific cleanup.setInterval
returns an interval ID that you can pass toclearInterval
to stop it.Generally, I’d say your code does not make a whole lot of sense in a React context, but in your case you could do something like this:
Seen as this is a React question, below is an example of using a
setInterval
inside a React Component. If your using some form of React Router the below code will also correctly unmount / mount etc.