summaryrefslogtreecommitdiffstats
path: root/modules/util/timer.go
blob: f9a7950709f4a2d687a6c0441c833e9449409f2c (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
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package util

import (
	"sync"
	"time"
)

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
	}
}