tempus
Version:
one rAF to rule them all
2 lines • 2.68 kB
JavaScript
var l=0;function m(){return l++}var r=typeof window<"u",u=r&&window.requestAnimationFrame,c=r&&window.cancelAnimationFrame,a=class{callbacks=[];fps;time=0;lastTickDate=performance.now();framesCount=0;constructor(e=Number.POSITIVE_INFINITY){this.fps=e}get isRelativeFps(){return typeof this.fps=="string"&&this.fps.endsWith("%")}get maxFramesCount(){return this.isRelativeFps?Math.max(1,Math.round(100/Number(this.fps.replace("%","")))):1}get executionTime(){return this.isRelativeFps?0:1e3/this.fps}dispatch(e,i){for(let t=0;t<this.callbacks.length;t++){let s=performance.now();this.callbacks[t]?.callback(e,i);let n=performance.now()-s;this.callbacks[t].samples?.push(n),this.callbacks[t].samples=this.callbacks[t].samples?.slice(-9)}}raf(e,i){if(this.time+=i,this.isRelativeFps)this.framesCount===0&&this.dispatch(e,i),this.framesCount++,this.framesCount%=this.maxFramesCount;else if(this.fps===Number.POSITIVE_INFINITY)this.dispatch(e,i);else if(this.time>=this.executionTime){this.time=this.time%this.executionTime;let t=e-this.lastTickDate;this.lastTickDate=e,this.dispatch(e,t)}}add({callback:e,priority:i,label:t}){if(typeof e!="function"){console.warn("Tempus.add: callback is not a function");return}let s=m();return this.callbacks.push({callback:e,priority:i,uid:s,label:t,samples:[]}),this.callbacks.sort((n,p)=>n.priority-p.priority),()=>this.remove(s)}remove(e){this.callbacks=this.callbacks.filter(({uid:i})=>e!==i)}},o=class{framerates;time;fps;usage;constructor(){this.framerates={},this.time=r?performance.now():0,this.usage=0,r&&requestAnimationFrame(this.raf)}add(e,{priority:i=0,fps:t=Number.POSITIVE_INFINITY,label:s=""}={}){if(r){if(typeof t=="number"||typeof t=="string"&&t.endsWith("%"))return this.framerates[t]||(this.framerates[t]=new a(t)),this.framerates[t].add({callback:e,priority:i,label:s});console.warn('Tempus.add: fps is not a number or a string ending with "%"')}}raf=e=>{if(!r)return;let i=e-this.time;this.time=e,this.fps=1e3/i;let t=performance.now();for(let n of Object.values(this.framerates))n.raf(e,i);let s=performance.now()-t;this.usage=s/i,requestAnimationFrame(this.raf)};patch(){r&&(window.requestAnimationFrame=(e,{priority:i=0,fps:t=Number.POSITIVE_INFINITY}={})=>e===this.raf||!e.toString().includes("requestAnimationFrame(")?u(e):(e.__tempusPatched||(console.log("patching",e.name,e),e.__tempusPatched=!0,e.__tempusUnsubscribe=this.add(e,{priority:i,fps:t,label:e.name})),e.__tempusUnsubscribe),window.cancelAnimationFrame=e=>{if(typeof e=="function"){e?.();return}return c(e)})}unpatch(){r&&(window.requestAnimationFrame=u,window.cancelAnimationFrame=c)}},h=new o;globalThis.Tempus=h;
//# sourceMappingURL=tempus.min.js.map