What happens in JavaScript if I never call the callback?

Suppose I have the following code

function myFunction(param, callback) {
    ...
    if (err) {
        console.log("error");
        console.log(err);
    }
    else {
        callback(data);
    }
}

      

If there is no error, a callback is called. In case of error, this is not the case. Suppose the calling function looks something like this:

myFunction(param, function(data) {
...
});

      

Are there any memory leak problems or similar? Is there a better way to handle this scenario?

+3


source to share


3 answers


A JavaScript object will not be eligible for reclamation if it is strongly reachable: that is, if it can be reached by traversing the graph of the object from the root object (which is basically equal to the global property, or possibly closed by -over, variable). Any object that can no longer be reached is no longer accessible via JavaScript and will be reclaimed by the GC (when the GC likes it).

In this case, the function object (callback) passed to myFunction

can only be reachable during the entire function call when it is available via a parameter callback

. Since the function-object cannot be reachable after the function (for example, it was not stored in a global property), then the function-object is eligible for reclamation - along with any function scopes it refers to unless they are no longer strongly accessible - as soon as the function completes.

So there is no "memory leak" in this case. However, imagine this case:

window.myCallbacks = []
function myFunction(param, callback) {
    ...
    window.myCallbacks.push(callback)  // hmm, maybe always strongly-reachable?
}

      



Happy coding.


Technically, a true smart JavaScript engine could detect that the named object is callback

no longer available (via callback

) in the if branch. I'm not sure if any of the JS engines actually got this far, but the question gets more interesting when it comes to the boundaries of functions bound in closures (and if that preserves all objects named by all variables, even those to which do not apply later, strongly -reachable).

+10


source


No need to worry about leaking memory with the callback. You might want to get a callback.



0


source


Adding to the above answer see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management . Where does he say:

This algorithm reduces the definition of "object is not needed" anymore to "object is not available".

This algorithm assumes knowledge of a set of objects called roots (In JavaScript, a root is a global object). Periodically, the garbage collector will start at these roots, find all the objects that refer to these roots, then all the objects that these roots refer to, etc. Based on the roots, the garbage collector will thus find all accessible objects and collect all unreachable objects.

0


source







All Articles