utils.js (1443B)
1 function delayByFrames(f, num_frames) { 2 function recurse(depth) { 3 if (depth == 0) 4 f(); 5 else 6 requestAnimationFrame(() => recurse(depth-1)); 7 } 8 recurse(num_frames); 9 } 10 11 // Returns a Promise which is resolved with the event object when the event is 12 // fired. 13 function getEvent(eventType) { 14 return new Promise(resolve => { 15 document.body.addEventListener(eventType, e => resolve(e), {once: true}); 16 }); 17 } 18 19 20 // Returns a Promise which is resolved with a "true" iff transient activation 21 // was available and successfully consumed. 22 // 23 // This function relies on Fullscreen API to check/consume user activation 24 // state. 25 async function consumeTransientActivation() { 26 try { 27 await document.body.requestFullscreen(); 28 await document.exitFullscreen(); 29 return true; 30 } catch(e) { 31 return false; 32 } 33 } 34 35 // Returns a `Promise` that gets resolved when `window` receives a "message" 36 // event with an `event.data` JSON string whose "type" field matches the given 37 // parameter. The promise is resolved with JSON-parsed `event.data`. 38 function receiveMessage(type) { 39 return new Promise((resolve) => { 40 window.addEventListener("message", function listener(event) { 41 if (typeof event.data !== "string") { 42 return; 43 } 44 const data = JSON.parse(event.data); 45 if (data.type === type) { 46 window.removeEventListener("message", listener); 47 resolve(data); 48 } 49 }); 50 }); 51 }