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

后端 未结 3 687
悲&欢浪女
悲&欢浪女 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:32

    As others have mentioned, setTimeout doesn’t spawn a thread. If you want a list of all the timeout ids (so you can cancel them, for example) then see below:


    I don’t think you can get a list of all timeout ids without changing the code when they are called. setTimeout returns an id—and if you ignore it, then it's inaccessible to your JavaScript. (Obviously the interpreter has access to it, but your code doesn't.)

    If you could change the code you could do this:

    var timeoutId = [];
    
    timeoutId.push(setTimeout(myfunc, 100));
    

    …Making sure that timeoutId is declared in global scope (perhaps by using window.timeoutId = []).


    Just off the top of my head, but to reimplement setTimeout you’d have to do something like this:

    var oldSetTimeout = setTimeout;
    setTimeout = function (func, delay) {
        timeoutId.push(oldSetTimeout(func, delay));
    }
    

    This isn’t tested, but it gives you a starting point. Good idea, molf!

    Edit: aularon's answer gives a much more thorough implementation of the above idea.

提交回复
热议问题