Delete the js code that is still running
P粉864872812
P粉864872812 2024-02-17 18:08:32
0
2
449

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>

P粉864872812
P粉864872812

reply all(2)
P粉344355715

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 to clearInterval 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:



sssccc
P粉083785014

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.

const {useState, useEffect} = React;

function Page() {
  const [counter, setCounter] = useState(0);
  useEffect(() => {
    const i = setInterval(() => {
       console.log(new Date());
       setCounter(c => c +1);
    }, 1000);
    return () => {
      console.log('umount');
      clearInterval(i);
    }
  }, []);
  return 
This is a page, and when unmounted will end the setInterval.
Counter: {counter}, time: {new Date().toLocaleString()}
Check console you will also see console logging of datetime finishes.
} function OtherInfo() { return
Notice how the timer stopped inside the console.
If you click Show Page the component will be mounted again, this is kind of the basis of how React Router works in a Single Page Application (SPA).
} function App() { const [pageVis, setPageVis] = useState(true); return
{pageVis && } {!pageVis && }
{pageVis && } {!pageVis && }
} const root = ReactDOM.createRoot(document.querySelector('#mount')); root.render();
sssccc
sssccc

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!