混合 timer.Ticker 与 timer.Tick / timer.After;

我正在玩频道,我在这里遇到了一些事情。我有一个循环,我想在一段设定的时间后停止,比如 5 秒,我还想将迭代去抖动 300 毫秒。


func pump() <-chan interface{} {

    c := make(chan interface{})


    // use for loop

    // stop after 5 seconds


    d := time.NewTicker(time.Millisecond * 2000)


    go func() {


    myLoop:

        for {

            select {

            case <-time.After(time.Second * 5):

                fmt.Println("Its five seconds")

                close(c)

                d.Stop()

                break myLoop

            default:

                c <- rand.Int()

                <-d.C

                fmt.Println("After wait / debounce")

            }

        }

    }()


    return c

}

虽然上面的内容似乎是去抖动的,但它永远不会触发达到 5 秒的情况。我有类似的结果time.Tick(time.Second * 5)


func pump() <-chan interface{} {

    c := make(chan interface{})


    // use for loop

    // stop after 5 seconds


    d := time.NewTicker(time.Millisecond * 2000)

    t := time.NewTicker(time.Second * 5)


    go func() {


    myLoop:

        for {

            select {

            case <-t.C:

                fmt.Println("Its five seconds")

                close(c)

                t.Stop()

                d.Stop()

                break myLoop

                // case <-d.C:

                //  fmt.Println("its a sleep")

            default:

                c <- rand.Int()

                //  // slow down

                <-d.C

                //  fmt.Println("After 3000 milliseconds")

            }

        }

    }()


    return c

}

func pump() <-chan interface{} {

    c := make(chan interface{})


    // use for loop

    // stop after 5 seconds


    d := time.NewTicker(time.Millisecond * 2000)

    t := time.NewTicker(time.Second * 5)


    go func() {

}

以上对我有用;使用另一个代码。我不明白为什么这会在前者失败的地方起作用,尤其是当 time.Tick() 在文档中被描述为等同于 time.NewTicker() 时,只暴露了通道 C。


我在这里错过了什么?代码片段有明显不同吗?


qq_笑_17
浏览 102回答 1
1回答

素胚勾勒不出你

根据我的评论:for {&nbsp; &nbsp;select {&nbsp; &nbsp; &nbsp; case <-time.After(time.Second * 5):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp;}}time.After每次迭代都会创建一个新的计时器 ( )。这意味着计时器永远不会触发(因为default)情况将始终被选中。您可以通过在循环 ( playground )之外创建计时器来防止这种情况发生:timer := time.After(time.Second * 5)myLoop:for {&nbsp; &nbsp;select {&nbsp; &nbsp; &nbsp; case <-timer:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break myLoop&nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp;}}你的第二个例子对我来说工作正常(见前面提到的游乐场)。请注意,我不确定这些中的任何一个是否会实现您正在寻找的结果,因为它没有真正定义。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go