Standard library / context

context.AfterFunc()

Schedule f in its own goroutine when ctx is done. The stop function may prevent execution, but does not wait for a started callback. Expected stdout: 'false\n'.

Formal Syntax & Structure

go syntaxgo
func AfterFunc(ctx Context, f func()) (stop func() bool)

Parameters & Attributes

NameTypeDescription
ctxContextContext whose completion is observed.
ffunc()Function to invoke; see callback timing and concurrency rules.

Return Value

(stop func() bool)

Stop function returning true only when it prevents callback execution.

Working Example

Example Snippetgo
package main
import (  "context"  "fmt")
func main() {  ctx, cancel := context.WithCancel(context.Background())  defer cancel()  done := make(chan struct{})  stop := context.AfterFunc(ctx, func() { close(done) })  defer stop()  cancel()  <-done  fmt.Println(stop())}
Go Reference