Skip to content

Instantly share code, notes, and snippets.

@umcconnell
Created November 26, 2019 18:00
Show Gist options
  • Save umcconnell/f5af0e6be7e1bf3466fba08cd265a9c0 to your computer and use it in GitHub Desktop.
Save umcconnell/f5af0e6be7e1bf3466fba08cd265a9c0 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);
}
@Kexplx
Copy link

Kexplx commented Feb 16, 2022

Nice idea using the braille tokens. Thanks

@ByteJoseph
Copy link

Thanks bro

@guyk-bp
Copy link

guyk-bp commented Jul 31, 2024

Any example for modifying the text while animating?
e.g. progress bar in percentage?

let loader = loadingAnimation("Loading (10%)…");

... // now what?

@ByteJoseph
Copy link

Any example for modifying the text while animating? e.g. progress bar in percentage?

let loader = loadingAnimation("Loading (10%)…");

... // now what?

Edit the Function

The loadingAnimation function creates a loader animation in the console.

function loadingAnimation(
    getText,
    chars = ["⠙", "⠘", "⠰", "⠴", "⠤", "⠦", "⠆", "⠃", "⠋", "⠉"],
    delay = 100
) {
    let x = 0;

    return setInterval(function() {
        process.stdout.write("\r" + chars[x++] + " " + getText());
        x = x % chars.length;
    }, delay);
}

Usage

The following example demonstrates how to use the loadingAnimation function to display a progress percentage that updates over time.

// Example usage
let progress = 0;
let loader = loadingAnimation(() => `Loading (${progress}%)…`);

// Simulate progress update
let progressInterval = setInterval(() => {
    progress += 10;
    if (progress > 100) {
        clearInterval(progressInterval);
        clearInterval(loader);
        console.log("\nLoading complete!");
    }
}, 500);

@guyk-bp
Copy link

guyk-bp commented Jul 31, 2024

Thanks!

@ByteJoseph
Copy link

Thanks!

🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment