Your challenge is to make an infinite loading screen, that looks like this:
Or, to be more specific:
- Take no input.
- Output
Loading..., with a trailing space, but no trailing newline. - Infinitely cycle through the chars
|,/,-and\: every 0.25 seconds, overwrite the last one with the next in the sequence. You can overwrite just the last character, or delete and rewrite the whole line, as longLoading...remains unchanged.
Rules
- The output text must look exactly as specified. Trailing newlines/spaces are acceptable.
- You should not wait 0.25 seconds before initially showing output - the first frame should be printed as soon as the program is run.
- Your program should be able to run indefinitely. For example, if you use a counter for frames, the counter should never cause an error by exceeding the maximum in your language.
- Although the waiting period between each "frame" should be 0.25 seconds, obviously this will never be exact - an error margin of 10% or so is allowed.
- You may submit a function, but it must print to
stdout. - You can submit an answer in a non-console (but still text-based) environment, as long as it is capable of producing the loading animation.
- This is code-golf, so the shortest solution (in bytes) wins. Standard code-golf loopholes apply.
- If possible, please provide a gif of your loading screen in action.
Example
Here is the C++ code I used to create the example (ungolfed):
#include <iostream>
#include <string>
#include <thread>
using namespace std;
int main() {
string cycle = "|/-\\";
int i = 0;
cout << "Loading... ";
while (true) {
// Print current character
cout << cycle[i];
// Sleep for 0.25 seconds
this_thread::sleep_for(chrono::milliseconds(250));
// Delete last character, then increase counter.
cout << "\b";
i = ++i % 4;
}
}
May the best golfer win!
-
4\$\begingroup\$ Can submissions wait 0.25 seconds before initially displaying output? \$\endgroup\$ETHproductions– ETHproductions2016年11月27日 20:42:02 +00:00Commented Nov 27, 2016 at 20:42
-
2\$\begingroup\$ No, but thanks for mentioning that, I'll add it to the rules @ETHproductions \$\endgroup\$FlipTack– FlipTack2016年11月27日 20:43:09 +00:00Commented Nov 27, 2016 at 20:43
-
\$\begingroup\$ Is a trailing newline (after the animating symbol) acceptable? \$\endgroup\$Copper– Copper2016年11月27日 20:43:58 +00:00Commented Nov 27, 2016 at 20:43
-
\$\begingroup\$ Of course :) @Copper \$\endgroup\$FlipTack– FlipTack2016年11月27日 20:44:52 +00:00Commented Nov 27, 2016 at 20:44
-
1\$\begingroup\$ @TheBitByte it means that, theoretically, nothing inside your program will cause it to error - such as a counter overflowing or reaching maximum recursion depth. \$\endgroup\$FlipTack– FlipTack2016年12月15日 06:57:23 +00:00Commented Dec 15, 2016 at 6:57
112 Answers 112
Swift 6, (削除) 108 (削除ここまで) (削除) 123 (削除ここまで) 121 bytes
C interop, gooooooooooooooooo...
import Darwin
let s=stdout
fputs("Loading... |",s)
while 0<1{"|/-\\".map{fputs("\u{8}\(0ドル)",s)
fflush(s)
usleep(250000)}}
(削除) We print to Never mind, sometimes reading the question in full is a good idea.stderr instead of stdout because stderr isn't buffered by default; this saves me a call to fflush(_:). (削除ここまで)
We use fputs(_:) instead of puts(_:) to avoid the trailing newline. (And before anyone asks, no, we can't just use printf, because printf, being a C function that uses the ... syntax for varargs, is not available in Swift.)
ForceLang, 130 bytes
Noncompeting, requires language features (datetime.wait) that postdate the question.
def w io.write
set z string.char 8
def d datetime.wait 250
w "Loading... "
label 1
w z+"|"
d
w z+"/"
d
w z+"-"
d
w z+"\"
d
goto 1
Rust, 196 bytes
use std::*;
use std::io::Write;
fn main(){let mut i=0;loop{print!("Loading... {}",['|','/','-','\\'][i]);io::stdout().flush();thread::sleep(time::Duration::from_millis(250));i=(i+1)%4;print!("\r")}}
Ungolfed with explanation:
// We have to use the std library before we can use the io, time, and thread modules
use std::*;
// We also have to have the std::io::Write trait in scope before we can use the functions it defines (like flush)
use std::io::Write;
// The main function
fn main() {
// Our counter. It has to be declared mutable so that we can change it
let mut i = 0;
// loop creates an infinite loop
loop {
// print the loading text with the current spinner char
// ['|','/','-','\'][i] must be used instead of "/-\\"[i] because Rust's strs and Strings don't allow indexing. :(
print!("Loading... {}", ['|','/','-','\'][i]);
// Flush stdout. Without this nothing will be displayed on the screen
io::stdout().flush();
// Sleep for 250 ms (0.25 secs)
thread::sleep(time::Duration::from_millis(250));
// Increment the counter
i = (i+1)%4;
// print a carriage return to clear the line
print!("\r")
}
}
-
\$\begingroup\$ codegolf.stackexchange.com/a/122770/45877 \$\endgroup\$Chad Baxter– Chad Baxter2017年05月25日 17:12:21 +00:00Commented May 25, 2017 at 17:12
Windows Batch, 109 bytes
This is just another solution in Windows Batch
@echo off
call:s ^|
call:s /
call:s -
call:s \
%0
:s
cls
echo Loading... %1
ping 1.1 -n 1 -w 250>nul
goto:eof
I'm not quite shure what's wrong with the pipesymbol.
-
\$\begingroup\$ The pipe is a special character in batch \$\endgroup\$SuperJedi224– SuperJedi2242016年12月26日 00:22:31 +00:00Commented Dec 26, 2016 at 0:22
C# - 111 bytes
Just added some "creative [ac]counting" to existing C# answers.
void G(){for(var i=0;;i=i%4+1){Console.Write("\rLoading... "+"|/-\\|"[i]);System.Threading.Thread.Sleep(250);}}
Human readable version.
void G()
{
for (var i = 0; ; i = i % 4 + 1)
{
Console.Write("\rLoading... " + "|/-\\|"[i]);
System.Threading.Thread.Sleep(250);
}
}
Ruby, 57 bytes
Same length as Conor O'Brien's answer, but a different approach:
%w(| / - \\).cycle{|c|$><<"Loading... #{c}\r";sleep 0.25}
Scala, 86 bytes
def t(i:Int=0):Any={print("\b"*12+"Loading... "+"|/-\\"(i));Thread sleep 250;t(i+1&3)}
Explanation:
def t(i:Int=0):Any={ //define a method t
print( //print...
"\b"*12+ //a backspace character repeated 12 times to delete everything
"Loading... "+ //the string "Loading...
"|/-\\"(i) //and the i-th char of the char in question
);
Thread sleep 250; //sleep 250ms
t(i+1&3) //call t with i incremented by one, but capped at 3
}
Like most other answers, it looks pretty standard console-like.
C#, (削除) 168 (削除ここまで) (削除) 136 (削除ここまで) (削除) 123 (削除ここまで) 109 Bytes
Golfed:
void S(){for(int a=0;;a++){Console.Write("\rLoading... "+"|/-\\"[a%=4]);System.Threading.Thread.Sleep(250);}}
Ungolfed:
void S()
{
for(int a = 0; ; a++)
{
Console.Write("\rLoading... " + "|/-\\"[a%=4]);
System.Threading.Thread.Sleep(250);
}
}
See it working here:
Edit: Simplified the array.
Edit2: For is way better for this.
-
\$\begingroup\$ Regarding the edit sugestion: You dont need the Console.Clear(). Check the result gif I put, and when in doubt, test it out first ;) \$\endgroup\$Gonçalo– Gonçalo2017年02月01日 13:15:59 +00:00Commented Feb 1, 2017 at 13:15
tcl, 79
while 1 {lmap c {| / - \\} {puts -nonewline stderr \rLoading...\ $c;after 250}}
assuming I can write to stderr instead of stdout
C, (削除) 92 (削除ここまで) (削除) 89 (削除ここまで) 82 bytes
i;f(){for(;;i=4)while(i--)dprintf(2,"\rLoading... %c","|\\-/"[i]),usleep(250000);}
T-SQL, 121 bytes
DECLARE @ CHAR W:SET @=IIF(@='/','-',IIF(@='-','\',IIF(@='\','|','/')))PRINT'Loading... '+@ WAITFOR DELAY'0:0:0.25'GOTO W
Yabasic, 83 bytes
An anonymous function that takes no input and outputs to the console in graphics mode. Does not function with TIO.
Clear Screen
?"Loading..."
Do
?@(1,11)Mid$("|/-\\",i+1,1)
Wait.25
i=Mod(i+1,4)
Loop
-
\$\begingroup\$ Can you use
iinstead ofi+1in Mid$? \$\endgroup\$12Me21– 12Me212018年05月17日 11:55:39 +00:00Commented May 17, 2018 at 11:55 -
\$\begingroup\$ @12Me21 Unfortunately not -
Mid$is 1-indexed in Yabasic, so the+1is necessary. You can see this in the context of this question here \$\endgroup\$Taylor Raine– Taylor Raine2018年05月17日 12:43:24 +00:00Commented May 17, 2018 at 12:43
Groovy, 60 bytes (削除) 59 bytes (削除ここまで), (削除) 61 bytes (削除ここまで)
print'Loading...';for(;;)'|/-\\'.any{print"$it\b";sleep 250}
(modified to work with later versions of groovy, removed ascii cast)
Stax, 24 bytes
Ñ!Δ╚«&╖ô^ô◙⌠≈%<╗∞█z9ÖoOT
Delays 15 frames between each change, which at default 60fps should be equal to 1/4th of a second.
Explanation
W`lAtv>!`"|/-\"{[+p{|,}15*|:F
W loop forever
`lAtv>!` push "Loading... "
"|/-\"{ F for each char in "|/-\"
[+p add to Loading and print
{|,}15* delay 1 frame 15 times
|: clear the screen
-
\$\begingroup\$ limiting your display to 30fps would mess with any of the programs here. \$\endgroup\$Razetime– Razetime2021年06月10日 02:57:11 +00:00Commented Jun 10, 2021 at 2:57
-
\$\begingroup\$ Hm. An error margin is allowed, and no fps requirements are specified. It should work fine on any modern browser. \$\endgroup\$Razetime– Razetime2021年06月10日 03:00:53 +00:00Commented Jun 10, 2021 at 3:00
-
\$\begingroup\$ I will specify a 60fps browser requirement then. \$\endgroup\$Razetime– Razetime2021年06月10日 03:03:44 +00:00Commented Jun 10, 2021 at 3:03
-
\$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$Razetime– Razetime2021年06月10日 03:05:39 +00:00Commented Jun 10, 2021 at 3:05
-
\$\begingroup\$ Move some things around to save a byte with foreach-short:
Ü╕Y¬Åâ┴═:÷Ç⌐G:○しろまる*╗0Ç├¿u▲さんかく\$\endgroup\$Khuldraeseth na'Barya– Khuldraeseth na'Barya2024年09月10日 16:59:43 +00:00Commented Sep 10, 2024 at 16:59
05AB1E, 26 bytes
[13ç"21⁄2... ""|/-\"NèJ?Ƶ–.W
[13ç"...""..."NèJ?Ƶ–.W # trimmed program
[ # forever...
ç # push character with codepoint...
13 # literal
"..." # push "Loading... "
è # push character in...
"..." # literal...
è # at index...
N # current index in loop...
è # modulo length of...
"..." # literal
? # output...
J # joined stack...
? # without trailing newline
.W # wait...
Ƶ– # 250...
.W # milliseconds
Python 3, 93 bytes
import time
while 1:print(end="Loading... "+"|/-\\"[int(time.time())%4]+"\r");time.sleep(.25)
Scratch, 98 bytes
define
forever
set[i v]to(((i)mod(4))+(1
say(join[Loading... ](letter(i)of[|/-\\]))for(.25)seconds
JavaScript + HTML, 48 + 20 = 68 bytes
setInterval(_=>a.innerHTML="\\|/-"[i++%4],i=250)
Loading... <a id=a>|
Since the animation is supposed to start immediately, I had to move the Loading text and the initial state of the animation to the HTML.
hyperscript, 86 bytes
Loading... <x _="init repeat forever increment n put '\\|/-'[n mod 4]into me wait 250"
Try it:
<script src="https://unpkg.com/[email protected]"></script>
Loading... <x _="init repeat forever increment n put '\\|/-'[n mod 4]into me wait 250"
init -- when the document is initialized
repeat forever
increment n -- increment initializes n to 0
put '\\|/-'[n mod 4]into me -- sets <x>'s innerHTML
wait 250 -- (250 milliseconds)
Japt, (削除) 29 (削除ここまで) 27 bytes
Oq`LoÃHg... {°g"|/-\\"#út@ß
Oq`...{°g"..."#út@ß
Oq :Overwrite the output with
`... : Compressed string "Loading... "
{ : Interpolate
° : Postfix increment the first input variable (defaults to 0)
g"..." : 0-based index into the literal string
#ú :250
t :Set a timeout of 250ms
@ :To run the following function
ß : Recursive call
Mindustry, 194 bytes
set s "|"
print "Loading... "
print s
printflush
wait 0.25
jump 8 notEqual s "|"
set s "/"
jump 1 equal
jump 11 notEqual s "/"
set s "-"
jump 1 equal
jump 0 notEqual s "-"
set s "\"
jump 1 equal
Must be connected with a message block (message1), which is used as stdout.
An interesting golf in this program is jump 1 equal: this is shorter than jump 1 always by 1 byte, and works due to the default arguments for jump being notEqual, x and false.
It expands to jump 1 equal x false, which is evaluated as true, because x is null and null s apparently equal to false. (Reminds me of strange JS comparisons.)
I'll add a GIF of it later.
Explore related questions
See similar questions with these tags.