Checking for pending calls

后端 未结 1 1416
面向向阳花
面向向阳花 2021-01-14 17:53

I\'m wondering if there is any way to check if there are any pending calls that\'ll be executed at some point, like for example a callback from an AJAX request or a timer (<

相关标签:
1条回答
  • 2021-01-14 18:48

    Considering that AJAX callbacks are dependent on the server response(success, failure), you can't define if they are pending to be called, until it's actually time to call them.

    But here's an idea how this checking can be achieved for setTimeout (and maybe setInterval):

    window.timeoutsRegistry = [];
    
    window.oldSetTimeout = window.setTimeout;
    
    window.setTimeout = function(func, delay) {
        var tId = window.oldSetTimeout(function() {
            try {
                func();
            }
            catch (exception) {
                //Do Error Handling
            }
        }, delay);
    
        var startedAt = (+new Date);
    
        window.timeoutsRegistry[tId] = {
            id: tId,
            callback: func,
            delay: delay,
            startedAt: startedAt,
            isPending: function () {
                var now = (+new Date);
    
                return ((startedAt + delay) > now);
            }
        };
    };
    
    for(var i =0; i < 10; i++) {
        setTimeout(function() {
            1+1;
        }, 200000);
    }
    
    
    console.log(window.timeoutsRegistry);
    
    var pending = window.timeoutsRegistry.filter(function(element) {
        return element.isPending();
    });
    
    console.log(pending);
    

    Some notes:

    • the filter method is not supported in all browsers
    • How to override a global function
    • What does +new Date do
    • A related question (just food for thought)
    0 讨论(0)
提交回复
热议问题