I want to implement a collection where elements can expire and be deleted. Because I have little experience with Javascript I can't find the best approach. In another languages I would have used a thread for iterating over the collection cleaning up expired elements. But in Javascript this is not possible and I couldn't think of solutions except using setInterval function. So every time an element is inserted a callback function will be registered for cleaning up the element later.
class Collection {
constructor() {
this.items = new Map()
}
put(key, value, expireIn) {
this.items.set(key, value)
setInterval(() => {
this.items.delete(key)
}, expireIn)
}
get(key) {
return this.items.get(key)
}
}
Do you think this approach can have some limit? For instance, is it fine call setInterval a lot of times? Are there any other way to implement it?
setTimeout(), notsetInterval()for a one-shot timer.