How to make a loading animation in Console Application written in JavaScript or NodeJs?
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);
})();
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.
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);