简体   繁体   中英

How to clear up this closure reference

For this code:

    var myObj = {
    callMeMaybe: function () {
        var myRef = this;
        var val = setTimeout(function () { 
            console.log('Time is running out!'); 
            myRef.callMeMaybe();
        }, 1000);
    }
};

myObj.callMeMaybe();
myObj = null;

if we call myObj.callMeMaybe() and then call myObj = null. We still can't cancel the call to callMeMaybe(); Anyway to solve this? Thanks.

You need to window.clearTimeout on val .

    var myObj = {
    callMeMaybe: function () {
        var myRef = this;
        this.val = setTimeout(function () { // made val visible outside
            console.log('Time is running out!'); 
            myRef.callMeMaybe();
        }, 1000);
    }
};

myObj.callMeMaybe();

window.clearTimeout( myObj.val );
myObj = null;

The clearTimeout() method clears a timer set with the setTimeout() method. The ID value returned by setTimeout() is used as the parameter for the clearTimeout() method.

clearTimeout(id_of_settimeout);

and the Number.MAX_VALUE is 1.7976931348623157e+308VALUE

I think this question can be done by clearTimeout loop 1.7976931348623157e+308VALUE times.

Does it take a long time?

Or you can get max id_of_settimeout by

max_id_of_settimeout = setTimeout(null,0);

Then loop back to zero

for (var i = max_id_of_settimeout;i>=0;i--){clearTimeout(i);}

Just my opinion.

Overwrite the callMeMaybe property with a new function, or null if you don't mind the TypeError.

myObj.callMeMaybe();
myObj.callMeMaybe = function(){};

Now when the asynchronous call is made from the setTimeout , it will invoke the empty function.


If you don't want to overwrite the function, then just set a flag on the object.

var myObj = {
    callMeMaybe: function () {
        var myRef = this;
        var val = setTimeout(function () { 
            console.log('Time is running out!'); 
            if (!myRef.prevent)
                myRef.callMeMaybe();
        }, 1000);
    }
};

myObj.callMeMaybe();
myObj.prevent = true; // will prevent the .callMeMaybe() in the setTimeout

But to be clear, you can not clear the closure reference itself. Objects are reference types, and JavaScript is pass by value.

This means when you do this:

var myRef = this;

...you've made a copy of the object reference. Because myRef is a local variable, it can't be touched from the outside. Best you can do is manipulate the object that is referenced, or make the myRef variable available to the outer scope.

...and ignore the down-voters. They don't understand how JavaScript works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM