4

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..

Mark Hollas
  • 1,107
  • 1
  • 16
  • 44
  • Whenever you add an item to the array, set a timer for 1 minute later that removes it when invoked. What's complicated about it? (this solution is far from technically elegant, but for such a small size problem that shouldn't matter at all) – Jon Nov 08 '13 at 08:53
  • If you only add them every 5 seconds, you only need to remove them every five seconds, surely? – lonesomeday Nov 08 '13 at 08:53
  • 1
    I'm not quite sure why you wouldn't want to use a timeout function. If you set a timer for each item you're set. – CaptainCarl Nov 08 '13 at 08:53
  • How might I set a timer for each item? – Mark Hollas Nov 08 '13 at 09:00

1 Answers1

1

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);
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98