106
\$\begingroup\$

Your challenge is to make an infinite loading screen, that looks like this:

enter image description here


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 long Loading... 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 , 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!

\$\endgroup\$
  • 3
    \$\begingroup\$ Can submissions wait 0.25 seconds before initially displaying output? \$\endgroup\$ – ETHproductions Nov 27 '16 at 20:42
  • 2
    \$\begingroup\$ No, but thanks for mentioning that, I'll add it to the rules @ETHproductions \$\endgroup\$ – FlipTack Nov 27 '16 at 20:43
  • \$\begingroup\$ Is a trailing newline (after the animating symbol) acceptable? \$\endgroup\$ – Copper Nov 27 '16 at 20:43
  • \$\begingroup\$ Of course :) @Copper \$\endgroup\$ – FlipTack Nov 27 '16 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 Dec 15 '16 at 6:57

93 Answers 93

1
\$\begingroup\$

Node, 72 bytes (70 with literal)

c=0;setInterval(_=>console.log('\x1BcLoading... '+'/-\\|'[c=-~c%4]),250)

If you replace \x1B with the literal escape character you can cut another 2 bytes. You don't need to call anything.

\$\endgroup\$
  • 1
    \$\begingroup\$ Would setInterval(_=>console.log('\x1BcLoading... '+'/-\\|'[c=-~c%4]),c=250) work since c is being mod-ed by four every time? \$\endgroup\$ – Zacharý Nov 29 '16 at 22:12
1
\$\begingroup\$

Python 3, 86 83 bytes

GIF to follow. Golfing suggestions welcome as this is still a little verbose. -3 bytes thanks to Flp.Tkc.

import time
i=1
while i:print(end="\rLoading... "+"/-\|"[i%4]);time.sleep(.25);i+=1
\$\endgroup\$
  • \$\begingroup\$ You can stick the \r before the Loading to save the costly bytes for end=. Note that this solution is extremely similar \$\endgroup\$ – FlipTack Nov 30 '16 at 17:40
  • \$\begingroup\$ @Flp.Tkc I could have sworn that there were no other Python answers on here. Thanks for the heads up. Also, that tip doesn't work as Python 3's print has the default end of \n which screws up the updating. Thanks anyway. \$\endgroup\$ – Sherlock9 Nov 30 '16 at 18:03
  • \$\begingroup\$ In that case you could do print(end="\rLoading... "+"/-\|"[i%4]) \$\endgroup\$ – FlipTack Nov 30 '16 at 21:40
1
\$\begingroup\$

F# (interactive), 81 bytes

async{while 1>0 do for c in"|/-\\"do printf"\rLoading... %O"c;do!Async.Sleep 250}

In order to run it in F# interactive, you have to pass it to Async.Start or Async.RunSynchronously.

For reference, a little longer non-async version:

while 1>0 do for c in"|/-\\"do printf"\rLoading... %O"c;System.Threading.Thread.Sleep 250

and a slightly outdated gif :)

enter image description here

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG. Nice answer :) \$\endgroup\$ – FlipTack Dec 3 '16 at 22:26
1
\$\begingroup\$

HTML/CSS 135 Bytes

Like my previous answer, but doesn't use a monospace font, saving 6 bytes (not 100% if that's allowed, so I separated the answers for separate voting).

Update - a non monospace font is allowed. This works!

@keyframes l{0%{content:'|'}25%{content:'/'}50%{content:'-'}75%{content:'\\'}}a:after{animation:l 1s infinite;content:'|'}
<a>Loading... 

\$\endgroup\$
  • \$\begingroup\$ The 0% frame seems unnecessary. \$\endgroup\$ – manatwork Nov 29 '16 at 8:41
  • \$\begingroup\$ @manatwork there so that it can repeat infinitely. \$\endgroup\$ – Ben Aubin Dec 13 '16 at 18:53
1
\$\begingroup\$

awk, 46 bytes

In awk, with some help from ANSI codes and the rotor comes piped in:

{while(i=1+i%4)print"Loading... "$i"\033[1A"}

Try it:

$ echo \|/-\\|awk -F '' '{while(i=1+i%4)print"Loading... "$i"\033[1A"}'
Loading...[|/-\]

One byte comes off if NF is replaced with 4. I didn't wait to see if i iterates to oblivion.

\$\endgroup\$
  • 1
    \$\begingroup\$ Does this have the space between the ... and the cycling chars? \$\endgroup\$ – FlipTack Dec 28 '16 at 9:38
  • \$\begingroup\$ @FlipTack Missed that, I stand corrected. \$\endgroup\$ – James Brown Dec 28 '16 at 11:14
1
\$\begingroup\$

tcl, 83

while 1 {lmap c {| / - \\} {puts -nonewline \rLoading...$c;flush stdout;after 250}}

Can be seen running on: https://goo.gl/BJmxV0

\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 57 bytes

@L CLS?"Loading... "+"|/-\"[I]:I=(I+1)MOD 4 WAIT 15 GOTO@L

Ungolfed:

@L                       'loop start
CLS                      'clear console
?"Loading... "+"|/-\"[I] 'construct our output and print
I=(I+1)MOD 4             'inc counter, MOD to prevent overflow
GOTO @L                  'loop
\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 51 46 bytes

CLS?"Loading... ";"|\-/"[3AND MAINCNT/15]EXEC.
\$\endgroup\$
1
\$\begingroup\$

PKod , 48 bytes ~ Non-Competing

Possibly the only way I can do this, as PKod only has one write-able variable lL=oo=ao=do=io=no=go=.ooo =|oyw=/oyw=-oyw=\oywl<

Explanation: l - Clear screen and since its the first char, allow printing no operation (NOP) chars
             L - NOP, thus print "L"
             =oo=ao=do=io=no=go=.ooo - Set as certain chars and print them.
             (space) - Another NOP, thus print a space
             =|oyw - Set char as "|", print it, then wait a quarter of a second and remove it
             =/oyw=-oyw=\oywl - Same as above, with different symbols to match the challenge
             < - Go back to the start

"Gif" (more like mp4): https://i.gyazo.com/577dd164313a6b2e5dbf40249efb435d.mp4

You can see quote marks around the code in the console, thats because cmd tries to do stuff with my "<" and would return an error. It's just to nicely pass the code to the interpeter without cmd interfering.

\$\endgroup\$
1
\$\begingroup\$

Bash, 100 bytes

while [ 1 ]; do for i in `echo '|/-\' | grep -o .`; do printf $'\rLoading...'$i;sleep 0.25;done;done

This is not nicely golfed, so please tell me where I can improve here.


This does work, and has been tested on a Raspbian Raspberry Pi, an Amazon server, and an Ubuntu machine. This would not work on a Solaris machine because the sleep command on those systems cannot take inputs less than 1.

\$\endgroup\$
1
\$\begingroup\$

C#, 183 180 178 170 161 140 bytes

I know a C# solution has already been posted, but this one is a fully functional console program (including usings) in less bytes!

Golfed

class P{static void Main(){for(int i=0;;){System.Console.Write("\rLoading... "+@"|/-\"[i=i++==3?0:i]);System.Threading.Thread.Sleep(250);}}}

Ungolfed

class P
{
    static void Main()
    {
        for (int i = 0; ;)
        {
            System.Console.Write("Loading... "+@"|/-\"[i = i++ == 3 ? 0 : i]);
            System.Threading.Thread.Sleep(250);
        }
    }
}

Yes, I'm probably very late, but I had to post it..!

EDIT: I figured someone else posted a 109 byte C# solution, oh well
EDIT 2: Thanks to the poster of the 109 byte C# solution, I managed to lose 3 more bytes by removing i<4 from my for loop, thanks!
EDIT 3: Removed C# 6 string interpolation and used good old + instead to save 2 more bytes.
EDIT 4: Not declaring a var for the animation characters anymore, instead I added them directly into the Write() method, saving another 8 bytes
EDIT 5: Removed the parameter string[]s from the Main method to save 9 bytes!
EDIT 6: Used carriage return instead of System.Console.Clear(), removed a using and moved the incrementing of i + the ternary inside of System.Console.Write(), all thanks to @CSharpie! (all this saved 21 bytes)

\$\endgroup\$
  • \$\begingroup\$ Instead of Console.Clear just use a carriage return infront of the string. c.Write("\rLoading... "+@"|/-\"[i]);. Then you probably can further reduce by getting rid of the using since you only need System.Console.Write("\rLoading... "+@"|/-\"[i]); You can put your ternary expression in there too, making it System.Console.Write("\rLoading... "+@"|/-\"[i=i++==4?0:i]); whilst also removing the i++ from the for-loop. \$\endgroup\$ – CSharpie Feb 1 '17 at 20:13
  • \$\begingroup\$ One small mistake, cant edit comments after 5 minutes so: Console.Write("\rLoading... "+ @"|/-\"[i=i++==3?0:i]); resulting in 142 bytes. \$\endgroup\$ – CSharpie Feb 1 '17 at 20:19
  • \$\begingroup\$ Woah @CSharpie that's some awesome improvements, thanks alot! I'll apply some of them, but I will have to explain why I rolled back the carriage return (I added it earlier): imgur GIF this is happening when the console window isn't wide enough, somehow. Doesn't happen using .Clear() \$\endgroup\$ – Metoniem Feb 2 '17 at 7:44
  • \$\begingroup\$ thats nothing you need to worry about. \$\endgroup\$ – CSharpie Feb 2 '17 at 8:04
  • \$\begingroup\$ @CSharpie Oh, really? I'll apply that as well then! Thank you very much :) I also discovered a weird exception happening using .Clear() but I don't think this is the right place to discuss that, so I posted it on SO instead \$\endgroup\$ – Metoniem Feb 2 '17 at 8:15
1
\$\begingroup\$

Python 3, 94 bytes

Okay. First answer. EDIT: SAVED 8 BYTES EDIT 2: SAVED 1 BYTE EDIT 3: SAVED 11 BYTES EDIT 4: SAVED 3 BYTES EDIT: SAVED 5 BYTES EDIT: SAVED 2 BYTES

import time
while 1:
 for f in 0,1,2,3:print("Loading...","|/-\\"[f],end="\r");time.sleep(.25)

Ungolfed:

import time
while True: # Loop forever
    for f in [0, 1, 2, 3]: # Loop four times
    print("Loading...", "|/-\\"[f], end="\r") # Print Loading... then the current frame
        time.sleep(0.25) # Wait 0.25 seconds
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! Nice answer, although there is a shorter python solution here. You might want to see tips for golfing in python so you can make your future answers shorter :) \$\endgroup\$ – FlipTack Dec 23 '16 at 20:42
  • \$\begingroup\$ I see you have a bit of extra whitespace particularly f += 1 can be replaced with f+=1 and f >= 3 can become f>=3. Additionally 0.25 can be replaced with .25 \$\endgroup\$ – Wheat Wizard Dec 23 '16 at 20:52
  • \$\begingroup\$ Also I think a can be defined as the string "|/-\\" without any issue. And since a is only referenced once you don't have to define it at all. \$\endgroup\$ – Wheat Wizard Dec 23 '16 at 20:53
  • 1
    \$\begingroup\$ Another thing I noticed is the fourth line is the same as f%=3. \$\endgroup\$ – Wheat Wizard Dec 23 '16 at 20:55
  • \$\begingroup\$ While True: is the same as While 1: \$\endgroup\$ – Wheat Wizard Dec 23 '16 at 20:57
1
\$\begingroup\$

PHP, 56 bytes

while(!usleep(25e4))echo"\rLoading... ",'\|/-'[@$i++%4];
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6) + HTML, 77 74 bytes

f=c=>setTimeout(f,250,-~c%4,o.value="Loading... "+"|/-\\"[~~c])
<input id=o

Try It

(f=c=>setTimeout(f,250,-~c%4,o.value="Loading... "+"|/-\\"[~~c]))()
<input id=o>

\$\endgroup\$
0
\$\begingroup\$

Swift 3, 75 bytes

do{"|/-\\".characters.map{print("\u{001B}[2J\nLoading... \($0)");sleep(1)}}

I need to use \u{001B} (ESCAPE) and [2J (clear screen) here because the old system API is deprecated in Swift 3 and I can't use \r on Mac/Linux. I would lose bytes if I had to use the length posix_spawn call or NSTask. I also hate having to access a string's CharacterView in order to map over each character. At least I saved some bytes by using do instead of a while loop.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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")
  }
}
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ The pipe is a special character in batch \$\endgroup\$ – SuperJedi224 Dec 26 '16 at 0:22
0
\$\begingroup\$

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);
    }
}
\$\endgroup\$
0
\$\begingroup\$

Ruby, 57 bytes

Same length as Conor O'Brien's answer, but a different approach:

%w(| / - \\).cycle{|c|$><<"Loading... #{c}\r";sleep 0.25}
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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:

enter image description here

Edit: Simplified the array.

Edit2: For is way better for this.

\$\endgroup\$
  • \$\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\$ – GonacFaria Feb 1 '17 at 13:15
0
\$\begingroup\$

tcl, 79

while 1 {lmap c {| / - \\} {puts -nonewline stderr \rLoading...\ $c;after 250}}

assuming I can write to stderr instead of stdout

\$\endgroup\$
0
\$\begingroup\$

shortC, 59 bytes

i;f(){O;;i=4)Wi--)dR2,"\rLoading... %c","|\\-/"[i]),U250000
\$\endgroup\$
0
\$\begingroup\$

C, 92 89 82 bytes

i;f(){for(;;i=4)while(i--)dprintf(2,"\rLoading... %c","|\\-/"[i]),usleep(250000);}
\$\endgroup\$
0
\$\begingroup\$

T-SQL, 121 bytes

DECLARE @ CHAR W:SET @=IIF(@='/','-',IIF(@='-','\',IIF(@='\','|','/')))PRINT'Loading... '+@ WAITFOR DELAY'0:0:0.25'GOTO W
\$\endgroup\$
0
\$\begingroup\$

><>, 68 Bytes, Noncompeting

Unfortunately there's no way to clear output in ><>, so this doesn't follow the challenge specifications exactly.

'/...gnidaoL'c>1-:?\~01g11g21g10g21p11p01p10pao
-\|           \ {o}/

Prints

Loading.../
Loading...-
Loading...\
Loading...|
Loading.../
.
.
.

Explanation:

'/...gnidaoL'

Pushes the ascii values for Loading.../ to the stack

             c>1-:?\~
              \ {o}/

Prints the top value of the stack, 11 times. Removes the counter when done.

 /                   01g11g21g10g21p11p01p10pao
-\|

Rotate the symbols '/ | \ -' in the codebox, and print a new line. So, after the first printing, we go to

'-...
\|/

And then

'\...
|/-

And so on.

\$\endgroup\$
0
\$\begingroup\$

C++ (224)

This certainly isn't the shortest code to do this. I like doing coding challenges, so I'm posting it anyway.

#include <iostream>
#include <string>
#include <thread>
using namespace std;int main(){string s = "|/-\\";int i=0;cout<<"Loading... ";while(1){cout<<s[i];this_thread::sleep_for(chrono::milliseconds(99));cout<<"\b";i=++i%4;}}
\$\endgroup\$
  • \$\begingroup\$ You can save 2 bytes by removing the spaces around =. \$\endgroup\$ – Wheat Wizard Jan 12 '18 at 17:46
0
\$\begingroup\$

Japt, 38 bytes

@Oq Oo`LoÃHg... `+"|/-\\"gW°%4)1
a#úiU

Try it online!

How it works

@Oq Oo`LoÃHg... `+"|/-\\"gW°%4)1
a#úiU

@               Declare a function...
 Oq               that clears the screen,
 Oo"Loading... "  prints this string,
 +"|/-\\"gW++%4   plus the spinner char (using a variable W),
 )1               and finally returns 1
                and implicitly store this function to U.

a       Call U once (return 1 is needed for this)
 #úiU   and call U every 250 milliseconds.

By the nature of Japt syntax, it's impossible to call U() directly (well, it's possible using JS directive $...$ but it's too long after all.) So we use U.a() method that calls U with numbers from 0 to infinity until U returns true. If you omit )1 at the end of the first line and try running it, your browser will hang.

Without the initial U() call, the output window will show the implicit output (seemingly random integer value) before first showing the Loading... text.

Finally, a#úiU actually translates to U.a(250 .i(U)), which registers the 250ms loop first and then passes the return value (which happens to be undefined) to U.a (which accepts optional function argument, but seems to do nothing special with undefined).

\$\endgroup\$
0
\$\begingroup\$

><> with -t.03 flag, 33 bytes

'o!vooooo|\-/ ...gnidaoL
{[4<o8o:

Try it online!

The only part of the specification this doesn't implement is that the first frame should be printed as soon as the program is run which seems rather strict and unobservable. The first frame here take 1.08 seconds to print, and every frame after that takes 0.24 seconds.

\$\endgroup\$

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.