Created
September 30, 2019 07:35
-
-
Save kayac-chang/5a8d8fd05c44a7e34079943b7993797f to your computer and use it in GitHub Desktop.
Execute a function repeatedly when frame change.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Execute a function repeatedly when frame change. | |
* @param {Function} func | |
* @param {any} args | |
* @return {stop} : Function to stop the loop | |
*/ | |
function frameLoop(func, ...args) { | |
let loop = true; | |
(async function execute() { | |
await nextFrame(); | |
func(...args); | |
if (loop) execute(); | |
})(); | |
return stop; | |
function stop() { | |
loop = false; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* wait by frame | |
* @return {Promise<number>} | |
*/ | |
export function nextFrame() { | |
return new Promise(execute); | |
function execute(resolve) { | |
const id = requestAnimationFrame(() => resolve(id)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment