Last active
November 19, 2017 17:38
-
-
Save josephspurrier/bb505a06953d664e4d56 to your computer and use it in GitHub Desktop.
Golang - Spinner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
// Make a channel for the spinner | |
c := make(chan int) | |
// Stop the spinner after a certain period of time | |
go func() { | |
time.Sleep(3000 * time.Millisecond) | |
c <- 1 | |
}() | |
// Show the spinner | |
loading(`|/-\`, c) | |
} | |
func loading(spinner string, c <-chan int) { | |
// Loop forever | |
for { | |
// Loop through frame string | |
for _, char := range spinner { | |
select { | |
// If loading is done, exit loop | |
case <-c: | |
fmt.Printf(" \r") | |
return | |
// If still loading, show one letter from string | |
default: | |
fmt.Printf("%s\r", string(char)) | |
time.Sleep(100 * time.Millisecond) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment