24

How to make a loading animation in Console Application written in JavaScript or NodeJs?

Example animation or other animation.

1. --
2. \
3. |
4. /
5. --

4 Answers 4

57

Not really possible in browser console. In Node.js:

var twirlTimer = (function() {
  var P = ["\\", "|", "/", "-"];
  var x = 0;
  return setInterval(function() {
    process.stdout.write("\r" + P[x++]);
    x &= 3;
  }, 250);
})();
3
  • 8
    Wow, that x &= 3; line is mystical. I would have written x = x % P.length; there (using the modulo operator instead of the and operator). That way, the code will also work if you add an element to P. In that case, x &= 4; or x &= P.length; will not work. Jan 18, 2016 at 6:59
  • >... or x &= P.length; will not work Why not? That just came to my mind as well Aug 5, 2019 at 10:07
  • 1
    @MatthisKohli: The & thing can only work when there is 2^k elements for some natural k, since it relies on bit operation. I wrote it that way because I knew there could only be 4 elements here; Joost is correct that more generally one would use %.
    – Amadan
    Aug 5, 2019 at 10:10
16

You can do it in the browser console as well:

var loading = (function() {
  var h = ['|', '/', '-', '\\'];
  var i = 0;

  return setInterval(() => {
    i = (i > 3) ? 0 : i;
    console.clear();
    console.log(h[i]);
    i++;
  }, 300);
})();

// clearInterval(loading) to stop it.
7

The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds) at each 250 ms the value in the p array is printed on the console. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. setInterval is used as a loop here. Using the clearInterval, the loop is breaked after 5000 ms using setTimeout.

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

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

You can try this package:

https://github.com/ErAz7/Termination

it supports

  • promise based tranition
  • easing transition functions
  • looped transition
  • frame rate control
  • playback speed control
  • canvas size options
  • colors

and some other useful features to create animations on terminal like a piece of cake!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.