'How to use setTimeout in JavaScript to print ellipsis on the same line at different times?
So this is my code so far:
let name = input.question("Please Provide a Name: ");
if (name === "Casper" || name === "casper"){
console.log("Access Granted");
function printMessage(){
console.log(.);
}
setTimeout(printMessage, 1000);
} else {
console.log("Access Denied");
}
What I want to do is print "..." after Access is Granted, but with each "." printing after a delay, and of course on the same line.
Thanks in advance to any help I get!
Solution 1:[1]
You can use setInterval() instead
let
counter = 0,
elipsisInterval = setInterval(() => {
counter++;
console.log(`Access Granted${".".repeat(counter)}`);
if (counter === 3) {
counter=0;
}
}, 1000)
.as-console-wrapper { max-height: 100% !important; top: 0; }
This will print
Access Granted.
Access Granted..
Access Granted...
Access Granted.
Access Granted..
Access Granted...
Each second Because console.log() defaults to end on a line break Apparently if you're on NodeJS (so not on the frontend) you can use
process.stdout.write("Access Granted")
process.stdout.write(".")
and it will stay on the same line
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mushroomator |
