Does the browser keep track of active timer IDs?

后端 未结 5 1280
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 09:34

Does the browser keep track of active setInterval and setTimeout IDs? Or is this solely up to the developer to keep track of?

If it does keep t

5条回答
  •  爱一瞬间的悲伤
    2021-02-05 09:54

    Update:

    There are 2 aspects to this question.

    1. Does the browser keep track of timer IDs?
    2. Are they accessible

    I can only presume for #1 (and later #2) that the OP means "are they tracked" in the general sense because as a Developer s/he would like control over them.

    In short, yes they are tracked (as @s_hewitt noted, as long values by the browser) and they can be managed by the developer by maintaining a reference to the timers when setup.

    As a developer you can control (e.g. stop) them by calling (clearInterval(handleRef), or clearTimeout(handleRef))

    However there is no default window.timers or similar collection that gives you a list of the existing timers - you will need to maintain that yourself if you feel you need to.

    function startPolling(delay){
      pollHandle = setInterval(doThis, delay);
    }
    function stopPolling(){
      clearInterval(pollHandle);
    }
    
    function doThisIn30minUnlessStopped(){
      timerHandle = setTimeout(doThisThing, 1800000);
    }
    function stop30minTimer(){
      clearTimeout(timerHandle);
    }    
    

    You simply need to create a variable reference to your timer, and if/when needed, clear it by name.

    When you load another page, all the timers are automatically cleared by the browser so you don't need to maintain a handle, and clear them unless you need/want to.

提交回复
热议问题