Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a JavaScript setTimeout function stop when page reloaded?

If I initiate a setTimeout function from the trigger, will the function stop when the page is reloaded?

I initiate a setTimeout function "periodic_update()" on the onload event of my page.

Is this creating multiple instances of the periodic_update() function process?

<body onload="init_page_onload()">

function init_page_onload() {
    periodic_update();      
}

function periodic_update() {  
        foo()

    setTimeout("periodic_update()", PERIODIC_UPDATE_REPEAT_PERIOD_MS )
}
like image 209
Doug Null Avatar asked Jan 17 '23 06:01

Doug Null


2 Answers

When page is reloaded the "previous" timer is discarded and a new one will start.

like image 152
Adriano Repetti Avatar answered Jan 20 '23 16:01

Adriano Repetti


In the browser, all JavaScript code is aborted when you leave the page, and run when you open the page. So timeouts will be cleared and set again when you reload a page.

If you want to persist a timeout, you could:

  • use a parent frame which doesn't reload
  • use localStorage (which allows you to persist data on the client's computer) to keep track of when the function was last called, and set the timeout appropriately on load
like image 42
pimvdb Avatar answered Jan 20 '23 14:01

pimvdb