-
Notifications
You must be signed in to change notification settings - Fork 0
/
setInterval.go
43 lines (34 loc) · 862 Bytes
/
setInterval.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main
import "time"
// Code taken from https://www.loxodrome.io/post/set-timeout-interval-go/
func setInterval(someFunc func(), milliseconds int, async bool) chan bool {
// How often to fire the passed in function
// in milliseconds
interval := time.Duration(milliseconds) * time.Millisecond
// Setup the ticket and the channel to signal
// the ending of the interval
ticker := time.NewTicker(interval)
clear := make(chan bool)
// Put the selection in a go routine
// so that the for loop is none blocking
go func() {
for {
select {
case <-ticker.C:
if async {
// This won't block
go someFunc()
} else {
// This will block
someFunc()
}
case <-clear:
ticker.Stop()
return
}
}
}()
// We return the channel so we can pass in
// a value to it to clear the interval
return clear
}