create a loading animation in typescript

index.ts
const loadingAnimation = () => {
    const frames = ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷'];

    let i = 0;
    const interval = setInterval(() => {
        process.stdout.write('\r' + frames[i]);
        i = (i + 1) % frames.length;
    }, 100);

    return {
        stop: () => {
            clearInterval(interval);
            process.stdout.write('\n');
        }
    };
};

// Example usage
const loader = loadingAnimation();
// Do some async task which takes time
setTimeout(() => {
    loader.stop();
    console.log('Task completed.');
}, 5000);
558 chars
25 lines

related categories

gistlibby LogSnag