summaryrefslogtreecommitdiff
path: root/internal/ctxutil/sleep.go
blob: 6965e8d185f279c248a2e530a284ad638fd4d4eb (plain)
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
package ctxutil

import (
	"context"
	"time"
)

// Sleep waits for the delay or exits early when the context is canceled.
// It returns true when the full delay elapsed.
func Sleep(ctx context.Context, delay time.Duration) bool {
	if delay <= 0 {
		select {
		case <-ctx.Done():
			return false
		default:
			return true
		}
	}

	timer := time.NewTimer(delay)
	defer timer.Stop()

	select {
	case <-ctx.Done():
		return false
	case <-timer.C:
		return true
	}
}