Home > Net >  Would the JavaScript code stop running when the tab is closed?
Would the JavaScript code stop running when the tab is closed?

Time:09-02

I have some Javascript code that will be run when a component has completed loading:

function HelloThere() {
     React.useEffect(() => {
         setTimeout(() => {
             // code to make a server call to write data to DB
         }, 60 * 1000);
    }, []);
    return <h1>Hello there</h1>;
}

My question is, if the code in the useEffect is hit (component is loaded) but the user closes the tab (or refresh browser) before 60 seconds timeout, would the code still be running in the background and write data to DB? Thanks for the help!

CodePudding user response:

No, the code won't run. I think you can verify this by using localStorage. Set a timeout, run the script, close the tab, and see if localStorage is updated or not.

For example:

setTimeout(() => {
  window.localStorage.setItem('timeout-test', 'update after tab is closed')
}, 5000);
  • Related