Reputation: 1137
I have been looking around for this but have turned up a blank
is it possible in javascript to create an instance of an object which has a set time to live, after which it would be destroyed?
a case would be where a item is added to an array every 5 seconds and shown in the visual, each item then should be removed after it have been in view for a minute. I hesitate to run a timeout function checking the array every second to clear them..
Upvotes: 4
Views: 2739
Reputation: 45106
OOP FTW. Why not create some sort of self removing object?
function SelfRemover(){//constructor
};
SelfRemover.prototype.addTo = function(arr) {
var me = this;
arr.push(me); //adding current instance to array
setTimeout(function() { //setting timeout to remove it later
console.log("Time to die for " + me);
arr.shift();
console.log(arr);
}, 60*1000)
}
Usage
var a = [];
setInterval(function(){new SelfRemover().addTo(a); console.log(a);}, 5*1000);
Upvotes: 1