Does a JavaScript setTimeout function stop when page reloaded?

允我心安 提交于 2019-12-19 10:32:12

问题


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 )
}

回答1:


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




回答2:


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



回答3:


When you reload the browser, the html, css and javascript are re-evaluated as part of building the DOM and render trees. Consequently, each instance of the timer function is disposed on page reload. So, no, you will not end up with multiple instances of that function.



来源:https://stackoverflow.com/questions/9619864/does-a-javascript-settimeout-function-stop-when-page-reloaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!