How can I show a list of every thread running spawned by setTimeout/setInterval

后端 未结 3 680
悲&欢浪女
悲&欢浪女 2021-02-01 22:11

I want to do this either by pure javascript or any sort of console in a browser or whatever.

Is it possible?

Thanks

Further explanations: I want to debug

3条回答
  •  一整个雨季
    2021-02-01 22:30

    Note that setTimeout() does not spawn new threads. Browser side scripting is not only single threaded, but the JavaScript evaluation shares the same single thread with the page rendering (Web Workers apart).

    Further reading:

    • How JavaScript Timers Work by John Resig

    You may want to build a timer manager yourself:

    var timerManager = (function () {
       var timers = [];
       return {
          addTimer: function (callback, timeout) {
             var timer, that = this;
             timer = setTimeout(function () {
                that.removeTimer(timer);
                callback();
             }, timeout);
             timers.push(timer);
             return timer;
          },
          removeTimer: function (timer) {
             clearTimeout(timer);
             timers.splice(timers.indexOf(timer), 1);
          },
          getTimers: function () {
             return timers;
          }
       };
    })();
    

    Then use it as follows:

    var t1 = timerManager.addTimer(function () {
       console.log('Timer t1 triggered after 1 second');
    }, 1000);
    
    var t2 = timerManager.addTimer(function () {
       console.log('Timer t2 triggered after 5 second');
       console.log('Number of Timers at End: ' + timerManager.getTimers().length);
    }, 5000);
    
    console.log('Number of Timers at Start: ' + timerManager.getTimers().length);
    

    The above will display the following result in the console:

    // Number of Timers at Start: 2
    // Timer t1 triggered after 1 second
    // Timer t2 triggered after 5 second
    // Number of Timers at End: 0
    

    Note that the timerManager implementation above uses the Array.indexOf() method. This has been added in JavaScript 1.6 and therefore not implemented by all browsers. However, you can easily add the method yourself by adding the implementation from this Mozilla Dev Center article.

提交回复
热议问题