1

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?

1
  • 1
    Use setTimeout(), not setInterval() for a one-shot timer. Commented May 17, 2020 at 17:45

1 Answer 1

2

Your approach is fundamentally sound. Your use of Intervals has a problem, though.

It looks like you set a separate Interval for each item in your collection, the purpose of which is to delete it when its time-to-live expires. But Intervals repeat until you cancel them. You should probably use a timeout here. And if somehow an item gets deleted from your collection be sure to cancel its timeout.

A more efficient way to handle this sort of thing:

  • don't use separate timeout for each object in your collection.
  • make your get() method check whether your item has expired, and return null if so.
  • set up an interval for each collection to run every so often (a few seconds or minutes) and delete all expired items.

I use a module called node-cache for this purpose. https://www.npmjs.com/package/node-cache It works flawlessly for me for months of uptime and counting.

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

Comments

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.