Implement JavaScript setInterval like functionality in golang

01 Feb 2022

In Go, the equivalent of setInterval would be the time.Ticker type, which allows you to repeatedly execute a function at a specified interval. Here is how you could use time.Ticker to implement the same functionality as setInterval in JavaScript:


package main

import (
	"fmt"
	"time"
)

func main() {
	// Create a new Ticker that will execute the "someFunction" function every 10 seconds
	ticker := time.NewTicker(10 * time.Second)

	// Use a channel to receive the Ticker's events
	done := make(chan bool)
	go func() {
		for {
			select {
			case <-ticker.C:
				// Execute the "someFunction" function
				someFunction()
			case <-done:
				// Stop the Ticker and exit the goroutine
				ticker.Stop()
				return
			}
		}
	}()

	// Stop the Ticker after some time
	time.Sleep(30 * time.Second)
	done <- true
}

func someFunction() {
	fmt.Println("executing someFunction")
}

In this example, the time.Ticker will execute the someFunction function every 10 seconds, and the time.Sleep call is used to stop the Ticker after 30 seconds. You can use the ticker.Stop method to stop the Ticker at any time, which will cause the time.Ticker goroutine to exit and stop executing the someFunction function.