0

What potential problem can arise if I am keeping data inside a global var cache = {} ?

Will it be collected by the garbage collector? Can I ensure it's persistent until the end of viewing?

Is there browser built-in functionality I can use so even next time opening the page I have the cached data ready?

Thanks.

1
  • 1
    Global variables are never collected by GC, because they are global Commented Aug 7, 2012 at 6:08

2 Answers 2

3

It sounds like you need to understand the lifetime of global data in javascript:

  1. During the lifetime of a given page, a global variable lasts until you clear it's value. It will never be garbage collected. Because it's global, it can never go out of scope.

  2. When the viewer goes to a new page in that window or closes that browser window, all javsacript data for that prior page is freed and is no longer available.

  3. There are three ways to persist data so it can be used in future views of that page or in other pages: 1) Cookies, 2) Local Storage, 3) Server storage. In all of these cases, the data would have to be retrieved from its storage location and put back into javascript.

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

Comments

1

The variable will exist as long as the page remains open. After it is closed (or navigated away from), it will be garbage collected.

If there is very little data in the cache, you can serialize it and store it as a cookie. For larger amounts of data, DOM Storage may be useful but it is not universally supported among browsers.

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.