Categories
JavaScript Answers

How to make a loading animation in console application written in JavaScript and Node.js?

Spread the love

Sometimes, we want to make a loading animation in console application written in JavaScript and Node.js.

In this article, we’ll look at how to make a loading animation in console application written in JavaScript and Node.js.

How to make a loading animation in console application written in JavaScript and Node.js?

To make a loading animation in console application written in JavaScript and Node.js, we can use timers and the process.stdout.write method to write the loading animation characters to the screen.

For instance, we write:

const P = ['\\', '|', '/', '-'];
let x = 0;
const loader = setInterval(() => {
  process.stdout.write(`\r${P[x++]}`);
  x %= P.length;
}, 250);

setTimeout(() => {
  clearInterval(loader);
}, 5000);

We call setInterval with a callback that calls process.stdout.write to write the characters in P with index x to the screen every 250 seconds.

Then we call setTimeout with a callback to clear the loader timer in 5 seconds.

Conclusion

To make a loading animation in console application written in JavaScript and Node.js, we can use timers and the process.stdout.write method to write the loading animation characters to the screen.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to make a loading animation in console application written in JavaScript and Node.js?”

Leave a Reply

Your email address will not be published. Required fields are marked *