A simple fn that aims to do a similar stale-while-revalidate thing:
// takes a request and a response mapping function. map must be able to accept a null value. Returns the network request (reload) on completion, a stale network request, or a cached network request.functionstale_while_revalidate(req,map,err=_=>{alert(_);throw_;}){letmost_recent=0;req=typeofreq==="string"?{url:req}:{...req})letstale_cache=caches.match(newRequest(req)).finally(()=>most_recent>0?null:(most_recent=1));letstale_fetch=fetch(newRequest({...req,"cache":"force-cache"})).finally(()=>most_recent>1?null:(most_recent=2));letreload_fetch=fetch(newRequest({...req,"cache":"reload"})).finally(()=>most_recent>2?null:(most_recent=3));const_next=()=>newPromise(r=>setTimeout(r,99)).then(_=>{letk=[];switch(most_recent){// no breakscase0:k.push(stale_cache);case1:k.push(stale_fetch);case2:k.push(reload_fetch);}letr=Promise.race(k);if(most_recent!=3)returnr.finally(()=>{_next();});returnr;}).then(map,err);_next();returnreload_fetch.catch(_=>stale_fetch).catch(_=>stale_cache).then(map,err);}
This doesn't handle visibility change refresh, though. I typed it up on a phone so please be forgiving...
Note that if you're writing a real-time API or similar; it's probably best to use an EventSource or WebSocket. EventSource is generally less work for the same output; though.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
A simple fn that aims to do a similar stale-while-revalidate thing:
This doesn't handle visibility change refresh, though. I typed it up on a phone so please be forgiving...
Note that if you're writing a real-time API or similar; it's probably best to use an EventSource or WebSocket. EventSource is generally less work for the same output; though.