Destroy the object after the set time

I searched for this, but appeared empty

is it possible in javascript to create an instance of an object that has a set time for life, after which it will be destroyed?

the case will be that an element is added to the array every 5 seconds and displayed visually, each element must then be deleted after it has been visible for a minute. I hesitate to run the timeout function, checking the array every second to clear them.

+4
source share
1 answer

OOP FTW. Why not create some kind of self-expressing 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)
}

Using

var a = [];
setInterval(function(){new SelfRemover().addTo(a); console.log(a);}, 5*1000);
0
source

All Articles