Created
May 22, 2023 17:29
-
-
Save Yizack/07694a749c8fc5f4d996a2bd50237939 to your computer and use it in GitHub Desktop.
Tween a number, increment number from 0 to a desired target within a specified duration in seconds. Get count number in callback function.
This file contains hidden or 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
/** Tween a number, increment number from 0 to a desired target within a specified duration in seconds. Get count number in callback function. | |
* @param {number} target | |
* @param {number} duration | |
* @param {function} callback | |
* @returns {Promise<void>} | |
* @example | |
* await tweenNumber({ target: 100, duration: 1 }, (n) => console.log(n)); | |
*/ | |
const tweenNumber = async ({ target, duration }, callback = (n = 0) => {}) => { | |
let count = 0; | |
while (count < target) { | |
const add = target / (60 * duration); | |
if (count + add > target) { | |
count = target; | |
} | |
else { | |
count += add; | |
} | |
await new Promise(resolve => setTimeout(resolve, duration * 1000 / 60)); | |
callback(count); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment