-
Notifications
You must be signed in to change notification settings - Fork 11
/
debounce-throttle.lua
57 lines (45 loc) · 1.27 KB
/
debounce-throttle.lua
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
49
50
51
52
53
54
55
56
57
-- from gmod.one with <3
-- https://github.com/Be1zebub/Small-GLua-Things/blob/master/debounce-throttle.lua
--[[ usage example:
local search = util.Throttle(function(query)
net.Start("logs/search")
net.WriteString(query)
net.SendToServer()
end, 250)
userinput.OnChange = function(me)
search(me:GetValue())
end
]]--
local function GenerateTimer(prefix)
local trace = debug.getinfo(2, "Sln")
return prefix .. "/" .. util.CRC(debug.traceback()) .. " / " .. trace.short_src .. ":" .. trace.currentline
end
-- delays call, if previous delayed rm old delay
function util.Debounce(func, timeout)
local timerName = GenerateTimer("util.Debounce")
return function(...)
local args = {...}
timer.Create(timerName, timeout, 1, function()
func(unpack(args))
end)
end
end
-- if previous called was recent, delay call
function util.Throttle(func, timeout)
local timerName = GenerateTimer("util.Throttle")
local lastCall
return function(...)
local args = {...}
local prevCall = lastCall
lastCall = SysTime()
local delta = prevCall and lastCall - prevCall
if delta and delta <= timeout then
timer.Create(timerName, timeout - delta, 1, function()
func(unpack(args))
end)
else
func(unpack(args))
timer.Create(timerName, timeout, 1, function() end)
end
end
end