Skip to content

Instantly share code, notes, and snippets.

@abc0990cba
Forked from umcconnell/loader.js
Created January 5, 2024 19:28
Show Gist options
  • Select an option

  • Save abc0990cba/ab50004afd120fa34b2ca201f0d4e575 to your computer and use it in GitHub Desktop.

Select an option

Save abc0990cba/ab50004afd120fa34b2ca201f0d4e575 to your computer and use it in GitHub Desktop.
Loading animation for node console
// Adapted from https://stackoverflow.com/questions/34848505/how-to-make-a-loading-animation-in-console-application-written-in-javascript-or
/**
* Create and display a loader in the console.
*
* @param {string} [text=""] Text to display after loader
* @param {array.<string>} [chars=["⠙", "⠘", "⠰", "⠴", "⠤", "⠦", "⠆", "⠃", "⠋", "⠉"]]
* Array of characters representing loader steps
* @param {number} [delay=100] Delay in ms between loader steps
* @example
* let loader = loadingAnimation("Loading…");
*
* // Stop loader after 1 second
* setTimeout(() => clearInterval(loader), 1000);
* @returns {number} An interval that can be cleared to stop the animation
*/
function loadingAnimation(
text = "",
chars = ["⠙", "⠘", "⠰", "⠴", "⠤", "⠦", "⠆", "⠃", "⠋", "⠉"],
delay = 100
) {
let x = 0;
return setInterval(function() {
process.stdout.write("\r" + chars[x++] + " " + text);
x = x % chars.length;
}, delay);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment