mini-scheduler
Version:
A mini scheduler for task handler in browser
7 lines (6 loc) • 2.39 kB
JavaScript
/*!
* mini-scheduler v1.0.0
* (c) 2021 bryce
* @license MIT
*/
;Object.defineProperty(exports,"__esModule",{value:!0});const e=()=>performance.now(),t=(e,t)=>{let n=e.pop();for(;e.length&&n;)t(n),n=e.pop()},n=Promise.resolve(),o=e=>n.then(e),r=e=>!!e&&e.toString().includes("Generator"),s=[];let i=!1,u=60,c=10,a=window.setTimeout;const m=[],w=t=>navigator?.scheduling?.isInputPending()||e()<t+1e3/u-c,l=n=>{const o=()=>{const r=e();let s=null;do{s=n.next()}while(!s.done&&w(r));if(s.done){const e=a===window.setTimeout?window.clearTimeout:window.cancelAnimationFrame;return void t(m,e)}const i=a(o);m.push(i)};return o};const p=()=>{const n=function*(){for(let e=0;e<s.length;e++){const t=(0,s[e])();if(r(t)){const e=a(l(t));m.push(e)}else yield t}s.length=0,i=!1}();return function o(){const r=e();let s=null;do{s=n.next()}while(!s.done&&w(r));if(s.done){const e=a===window.setTimeout?window.clearTimeout:window.cancelAnimationFrame;return void t(m,e)}const i=a(o);m.push(i)}},d=e=>{const{fps:t=60,renderTime:n=10,funcType:o="setTimeout"}=e;if(u<=0||u>120)throw new Error(`fps must between 0~120, instead of ${u}`);if(c<=0||c>=1e3/60)throw new Error(`fps must between 0~${Math.floor(1e3/60)}, instead of ${c} ms`);if(!["setTimeout","requestAnimationFrame"].includes(o))throw new TypeError("funcType must be window.setTimeout or window.requestAnimationFrame");u=t,c=n,a="setTimeout"===o?window.setTimeout:window.requestAnimationFrame};exports.asyncPool=async(e,t,n)=>{const o=[],r=[];for(const s of t){const i=Promise.resolve().then((()=>n(s,t)));if(o.push(i),e<=t.length){const t=i.then((()=>r.splice(r.indexOf(t),1)));r.push(t),r.length>=e&&await Promise.race(r)}}return await Promise.all(o)},exports.clearTimers=t,exports.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},exports.getTime=e,exports.isGenerator=r,exports.nextTick=o,exports.ts=(e,t,n={fps:60,renderTime:10,funcType:"setTimeout"})=>{d(n);for(let n=0;n<e.length;n++)r=()=>t(e[n],n,e),s.includes(r)||s.push(r),i||(i=!0,o(p()));var r},exports.tsGenerator=(e,t={fps:60,renderTime:10,funcType:"setTimeout"})=>{if(!r(e))throw new TypeError("payload func must be a generator ");d(t);const n=a(l(e));m.push(n)};