Skip to content

Instantly share code, notes, and snippets.

@Yizack
Created May 22, 2023 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yizack/07694a749c8fc5f4d996a2bd50237939 to your computer and use it in GitHub Desktop.
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.
/** 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