Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hack:) node的字符界面的进度展示 #17

Open
hufeng opened this issue Sep 21, 2017 · 1 comment
Open

hack:) node的字符界面的进度展示 #17

hufeng opened this issue Sep 21, 2017 · 1 comment

Comments

@hufeng
Copy link
Owner

hufeng commented Sep 21, 2017

《The go programming language》中一个非常棒的小例子的时候
一个非常不错的字符界面的进度展示

package main
  
import (
        "fmt"
        "time"
)


func main() {
        go spinner(100 * time.Millisecond)
        const n = 45
        fibN := fib(n)
        fmt.Println("\rFib(%d) = %d\n", n, fibN)
}


func spinner(delay time.Duration) {
        for {
                for _, r := range `-\|/` {
                        fmt.Printf("\r%c", r)
                        time.Sleep(delay)
                }
        }
}

func fib(n int) int {
        if n < 2 {
                return n
        } else {
                return fib(n -1) * fib(n -2)
        }
}

联想到之前想制作一个node版本的,于是照猫画虎hack一下

const delay = time => {
  return new Promise(resolve => setTimeout(resolve, time));
};

async function spinner(time) {
  while (true) {
    const flag = ['-', '\\', '|', '/'];
    for (let f of flag) {
      process.stdout.write(`\r${f}`);
      await delay(time);
    }
  }
}

spinner(60);

happy hacking 👍

@hufeng
Copy link
Owner Author

hufeng commented Sep 26, 2017

简单的做了个抽取
https://github.com/hufeng/simple-indicator
直接使用yarn添加依赖

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant