1

Is it possible to set an expiration of an element inside the array? For example, I added element "A" inside an array and after n Hours it is automatically removed from the array.

If it is possible, then can you please provide me an example?

I'm newbie to javascript and node js so please don't go way too complicated. and also please don't mind if I have added silly question.

Thanks in advance!

1 Answer 1

1

You can simulate an expiration by using setTimeout to execute a callback function which deletes the item in the array after a certain delay:

const array = [1, 2, 3]

console.log('Before: ', array)

function setExpiration(array, itemIndex, delay){
  setTimeout(() => array.splice(itemIndex, 1), delay)
}

setExpiration(array, 1, 2000)

setTimeout(() => console.log('After: ', array), 2001)

Sign up to request clarification or add additional context in comments.

7 Comments

As per my understanding, I have to manually set a timeout for each element. What if elements inside an array are automatically being added. So how can I ensure that each element has its own auto expiration?? because I cannot manually add the timeout function for each if there are so many elements inside it...
@VenkatLohithDasari It would be possible to add a timeout for each item with a loop.
something like this?? for(var i = 0; i<array.length; i++){setTimeout(() => array.splice(i, 1), 2000)}; This way, the first element will be deleted in just 2 seconds but for the next element, it will be a total of 4 seconds to get deleted if I assume that both elements are added at same time.
@VenkatLohithDasari "but for the next element, it will be a total of 4 seconds to get deleted" - It will not actually. It will still take 2 seconds.
does that mean for loop executes code for each element simultaneously?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.