~/From setInterval to Ticker

Oct 20, 2024


A ticker in Go works similarly to JavaScript’s setInterval, in that it runs at regular intervals.

Example Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
   package main

   import (
       "fmt"
       "time"
   )

   func main() {
       duration := 5 * time.Second
       ticker := time.NewTicker(duration)
       defer ticker.Stop() // Ensure ticker stops when the function exits

       loop := 0
       for range ticker.C {
           loop++
           fmt.Printf("Checking iteration %d\n", loop)

           if loop == 2 {
               fmt.Println("Stopping ticker after 2 iterations.")
               break
           }
       }
   }

The .C field is a channel that receives a value for every tick. You can range over or select on this channel to perform periodic tasks

1
2
3
4
        select {
        case <-ticker.C: // Receive from the ticker's .C channel
            fmt.Println("Tick at", t)
        }

References

Tags: [Go]