From 934355dd09aa8b7e8993759b678af063b56b9fc6 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sun, 23 Aug 2020 12:43:53 -0400 Subject: Add promiseAnimationFrame function (#752) --- .eslintrc.json | 1 + ext/mixed/js/core.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/.eslintrc.json b/.eslintrc.json index 663e9003..558fd928 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -108,6 +108,7 @@ "deferPromise": "readonly", "clone": "readonly", "generateId": "readonly", + "promiseAnimationFrame": "readonly", "DynamicProperty": "readonly", "EventDispatcher": "readonly", "EventListenerCollection": "readonly" diff --git a/ext/mixed/js/core.js b/ext/mixed/js/core.js index 5bee4670..c5c6fef2 100644 --- a/ext/mixed/js/core.js +++ b/ext/mixed/js/core.js @@ -258,6 +258,34 @@ function promiseTimeout(delay, resolveValue) { return promise; } +function promiseAnimationFrame(timeout=null) { + return new Promise((resolve) => { + let timer = null; + let frameRequest = null; + const onFrame = (time) => { + frameRequest = null; + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + resolve({time, timeout: false}); + }; + const onTimeout = () => { + timer = null; + if (frameRequest !== null) { + cancelAnimationFrame(frameRequest); + frameRequest = null; + } + resolve({time: timeout, timeout: true}); + }; + + frameRequest = requestAnimationFrame(onFrame); + if (typeof timeout === 'number') { + timer = setTimeout(onTimeout, timeout); + } + }); +} + /* * Common classes -- cgit v1.2.3