Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to delete callback function after being called/executed in JavaScript?

I have a web-app that polls for data periodically to 3rd party services (say Facebook, Twitter, and so on). This poll/request is made via JSONP (to avoid cross-domain issue).

For example, a simple request would be something like this:

function jsonp_callback() {
    // Do something
}

var url = 'http://some.service.com/getresult?callback=jsonp_callback';
$http.jsonp(url);

However since there can be another type of request that can be made at any given time (for example: to send or post an update), I created a wrapper to handle the callbacks.

The implementation is something like this:

// Callback handler
var myCb = (function() {
    var F = function() {};
    F.prototype.fn = {};
    F.prototype.create = function(fn, scope) {
        var self = this;
        var id = new Date().getTime();
        self.fn[id] = function() {
            if (typeof fn === 'function') {
                fn.call(scope);
            }
        }
        return 'myCb.fn.' + id;
    }
    return new F();
})();

// JSONP request
var cb = myCb.create(function() {
    // Do something
});
var url = 'http://some.service.com/getresult?callback=' + cb;
$http.jsonp(url);

If you notice, after some time, the myCb.fn will be bloated will callbacks that were old or have already executed. Mu question is, do I need to create a mechanism to garbage-collect those who have been executed and no longer needed?

like image 477
Goni Avatar asked Feb 09 '26 15:02

Goni


1 Answers

You don't necessarily need to remove old callbacks, if you will only make a few calls per page, but if your page is a long running one and makes calls repeatedly it could be a good idea to delete them.

The "mechanism" could be as simple as

delete self.fn[id];

after calling the function.

like image 118
Matti Virkkunen Avatar answered Feb 12 '26 15:02

Matti Virkkunen



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!