How can the countdown effect be implemented in Go language?

In Go language, you can use the Ticker type in the time package to achieve a countdown effect. Here’s a simple example code:

package main

import (
	"fmt"
	"time"
)

func main() {
	duration := 10 // 倒计时时长,单位为秒

	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	for i := duration; i > 0; i-- {
		fmt.Printf("倒计时:%d 秒\n", i)
		<-ticker.C
	}

	fmt.Println("倒计时结束!")
}

In the code above, we first define the duration of the countdown and then create a Ticker object that sends a time value to the ticker.C channel every 1 second. In the loop, we continuously receive time values from the channel and output the remaining time of the countdown until it ends. Finally, we output a message indicating the end of the countdown.

Running the code above will allow you to see the countdown effect in action.

bannerAds