Skip to content

Instantly share code, notes, and snippets.

@karupanerura
Created December 13, 2018 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karupanerura/bce40bb9fd32761960e12c58d30db1d5 to your computer and use it in GitHub Desktop.
Save karupanerura/bce40bb9fd32761960e12c58d30db1d5 to your computer and use it in GitHub Desktop.
basic event loop example
package main
import (
"fmt"
"time"
)
func entrypoint() {
fmt.Println("1")
setTimeout(func() {
fmt.Println("2")
}, time.Second)
setTimeout(func() {
fmt.Println("3")
setTimeout(func() {
fmt.Println("4")
}, time.Second)
}, 2*time.Second)
}
package main
import (
"time"
)
var eventBuffer []*eventHandler
type eventHandler struct {
canFire func() bool
onFire func()
}
func setTimeout(cb func(), d time.Duration) {
t := time.Now().Add(d)
eventBuffer = append(eventBuffer, &eventHandler{
canFire: func() bool {
now := time.Now()
return now.After(t) || now.Equal(t)
},
onFire: cb,
})
}
func main() {
entrypoint()
for len(eventBuffer) > 0 {
for i, eh := range eventBuffer {
if eh.canFire() {
eventBuffer = append(eventBuffer[0:i], eventBuffer[i+1:]...)
eh.onFire()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment