我有一个永远循环,它有一个 Timer 变量,在一段时间后执行一个函数。
package main
import (
fmt "fmt"
"time"
)
func exe() {
fmt.Println("10-seconds-of-time-is-done")
}
func t() {
var timerCheck *time.Timer
fmt.Println("here's the timerCheck", timerCheck)
for {
timerCheck = time.AfterFunc(10*time.Second, func() { exe() })
fmt.Println("exiting-from-function-t")
return
}
}
func main() {
t()
fmt.Println("waiting-inside-main")
time.Sleep(20 * time.Second)
}
Run Code Online (Sandbox Code Playgroud)
这是输出。我不明白该函数t()立即返回,而是在 10 秒后timerCheck执行其exe()函数。
here's the timerCheck <nil>
exiting-from-function-t
waiting-inside-main
10-seconds-of-time-is-done
Run Code Online (Sandbox Code Playgroud)
这怎么可能?在标准库中,关于AfterFunc
// AfterFunc waits for the duration to elapse and then calls f
// in …Run Code Online (Sandbox Code Playgroud)