Skip to content

Instantly share code, notes, and snippets.

@kayac-chang
Created September 30, 2019 07:35
Show Gist options
  • Save kayac-chang/5a8d8fd05c44a7e34079943b7993797f to your computer and use it in GitHub Desktop.
Save kayac-chang/5a8d8fd05c44a7e34079943b7993797f to your computer and use it in GitHub Desktop.
Execute a function repeatedly when frame change.
/**
* 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;
}
}
/**
* 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