最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom events - Does a JavaScript setTimeout function stop when page reloaded? - Stack Overflow

programmeradmin3浏览0评论

If I initiate a setTimeout function from the <body onload...> 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 )
}

If I initiate a setTimeout function from the <body onload...> 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 )
}
Share Improve this question edited Jan 22, 2023 at 12:39 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 8, 2012 at 15:10 Doug NullDoug Null 8,32717 gold badges77 silver badges168 bronze badges 1
  • 3 FYI, it is best practise to pass a function to setTimeout rather than a string; use setTimeout(periodic_update, PERIODIC_UPDATE_REPEAT_PERIOD_MS ) instead. – Matt Commented Mar 8, 2012 at 15:14
Add a ment  | 

3 Answers 3

Reset to default 9

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

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 puter) to keep track of when the function was last called, and set the timeout appropriately on load

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.

发布评论

评论列表(0)

  1. 暂无评论