Time Based Cache Invalidation

Cache with time-based invalidation supporting stale-while-revalidate for fresh data with background refresh.

JavascriptData Fetching

Code

javascriptsnippet
1 line
export function twrCache(fetcher,{freshTime=60000,staleTime=300000}={}){const cache=new Map();async function get(key){const entry=cache.get(key);if(entry){const age=Date.now()-entry.time;if(age<freshTime)return entry.value;if(age<staleTime){refresh(key);return entry.value;}}return await refresh(key);}async function refresh(key){const value=await fetcher(key);cache.set(key,{value,time:Date.now()});return value;}return{get,invalidate:(key)=>cache.delete(key),clear:()=>cache.clear()};}

How it works

The code’s whole job belongs to the functions twrCache, get and refresh.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The result comes back as an object carrying get.

What to watch for

  • The guard age<freshTime short-circuits the flow with an early return when its condition holds.

Putting it to use

The main signature reads export function twrCache(fetcher,{freshTime=60000,staleTime=300000}={})

twrCache is the public entry point; everything else in the file exists to support it.

The call returns get.

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `twrCache`, `get`, `refresh` at load time.
What does `twrCache` return?
An object carrying `get`.