Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for pending calls

Tags:

javascript

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 (setTimeout).

Something like checking the entire stack of the engine that is running JavaScript.

like image 764
alexandernst Avatar asked Dec 10 '25 01:12

alexandernst


1 Answers

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)
like image 112
undefined Avatar answered Dec 12 '25 15:12

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!