aboutsummaryrefslogtreecommitdiffstats
path: root/modules/util/timer.go
blob: d598fde73ad272958abfb3d62a9a2fdf77fa1c1e (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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package util

import (
	"sync"
	"time"
)

// StopTimer is a utility function to safely stop a time.Timer and clean its channel
func StopTimer(t *time.Timer) bool {
	stopped := t.Stop()
	if !stopped {
		select {
		case <-t.C:
		default:
		}
	}
	return stopped
}

func Debounce(d time.Duration) func(f func()) {
	type debouncer struct {
		mu sync.Mutex
		t  *time.Timer
	}
	db := &debouncer{}

	return func(f func()) {
		db.mu.Lock()
		defer db.mu.Unlock()

		if db.t != nil {
			db.t.Stop()
		}
		var trigger *time.Timer
		trigger = time.AfterFunc(d, func() {
			db.mu.Lock()
			defer db.mu.Unlock()
			if trigger == db.t {
				f()
				db.t = nil
			}
		})
		db.t = trigger
	}
}