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!
CodePudding user response:
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)