Time Based Cache Invalidation
Cache with time-based invalidation supporting stale-while-revalidate for fresh data with background refresh.
Code
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<freshTimeshort-circuits the flow with an earlyreturnwhen 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
Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.