Does the browser keep track of active timer IDs?

后端 未结 5 1260
没有蜡笔的小新
没有蜡笔的小新 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

    You can add such global timers tracking by overriding the setTimeout/seInterval functions. As a bonus you easily add code when a timer is set or popped, track live timers or popped timers, etc...

    For example:

    timers = {}; // pending timers will be in this variable
    originalSetTimeout = window.setTimeout;
    // override `setTimeout` with a function that keeps track of all timers
    window.setTimeout = function(fu, t) {
        var id = originalSetTimeout(function() {
            console.log(id+" has timed out");
            delete timers[id]; // do not track popped timers 
            fu();
        }, t);
        // track this timer in the `timers` variable
        timers[id] = {id:id,  setAt: new Date(),  timeout: t};
        console.log(id+" has been set to pop in "+t+"ms");
    }
    // from this point onward all uses of setTimeout will be tracked, logged to console and pending timers will be kept in the global variable "timers".
    

提交回复
热议问题