UNPKG

mini-scheduler

Version:

A mini scheduler for task handler in browser

7 lines (6 loc) 2.57 kB
/*! * mini-scheduler v1.0.0 * (c) 2021 bryce * @license MIT */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["mini-scheduler"]={})}(this,(function(e){"use strict";const t=()=>performance.now(),n=(e,t)=>{let n=e.pop();for(;e.length&&n;)t(n),n=e.pop()},o=Promise.resolve(),i=e=>o.then(e),r=e=>!!e&&e.toString().includes("Generator"),s=[];let u=!1,c=60,a=10,l=window.setTimeout;const m=[],d=e=>navigator?.scheduling?.isInputPending()||t()<e+1e3/c-a,f=e=>{const o=()=>{const i=t();let r=null;do{r=e.next()}while(!r.done&&d(i));if(r.done){const e=l===window.setTimeout?window.clearTimeout:window.cancelAnimationFrame;return void n(m,e)}const s=l(o);m.push(s)};return o};const w=()=>{const e=function*(){for(let e=0;e<s.length;e++){const t=(0,s[e])();if(r(t)){const e=l(f(t));m.push(e)}else yield t}s.length=0,u=!1}();return function o(){const i=t();let r=null;do{r=e.next()}while(!r.done&&d(i));if(r.done){const e=l===window.setTimeout?window.clearTimeout:window.cancelAnimationFrame;return void n(m,e)}const s=l(o);m.push(s)}},p=e=>{const{fps:t=60,renderTime:n=10,funcType:o="setTimeout"}=e;if(c<=0||c>120)throw new Error(`fps must between 0~120, instead of ${c}`);if(a<=0||a>=1e3/60)throw new Error(`fps must between 0~${Math.floor(1e3/60)}, instead of ${a} ms`);if(!["setTimeout","requestAnimationFrame"].includes(o))throw new TypeError("funcType must be window.setTimeout or window.requestAnimationFrame");c=t,a=n,l="setTimeout"===o?window.setTimeout:window.requestAnimationFrame};e.asyncPool=async(e,t,n)=>{const o=[],i=[];for(const r of t){const s=Promise.resolve().then((()=>n(r,t)));if(o.push(s),e<=t.length){const t=s.then((()=>i.splice(i.indexOf(t),1)));i.push(t),i.length>=e&&await Promise.race(i)}}return await Promise.all(o)},e.clearTimers=n,e.getAsyncFunc=e=>{let t;switch(e){case"setTimeout":t=window.setTimeout;break;case"requestAnimationFrame":t=window.requestAnimationFrame;break;default:throw new Error("currently only support 'setTimeout' | 'requestAnimationFrame' types")}return t},e.getTime=t,e.isGenerator=r,e.nextTick=i,e.ts=(e,t,n={fps:60,renderTime:10,funcType:"setTimeout"})=>{p(n);for(let n=0;n<e.length;n++)o=()=>t(e[n],n,e),s.includes(o)||s.push(o),u||(u=!0,i(w()));var o},e.tsGenerator=(e,t={fps:60,renderTime:10,funcType:"setTimeout"})=>{if(!r(e))throw new TypeError("payload func must be a generator ");p(t);const n=l(f(e));m.push(n)},Object.defineProperty(e,"__esModule",{value:!0})}));