Skip to content

Commit

Permalink
fix: allow fractional seconds in throttle
Browse files Browse the repository at this point in the history
  • Loading branch information
aarondill committed Jan 17, 2024
1 parent 24ea0de commit 39e8f84
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions util/throttle.lua
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
local gtimer = require("gears.timer")
---Returns a throttled version of f
---@param f fun(...: unknown): any
---@param delay integer seconds
---@return fun(...: unknown)
local function throttle(f, delay)
---@type integer
local last_called
-- We have to use a timer to allow milliseconds (os.time can only support seconds)
local timer = gtimer.new({
timeout = delay,
single_shot = true, -- only run once
})
return function(...)
-- We've already called, and it was too soon
if last_called and os.difftime(last_called, os.time()) < delay then return end
last_called = os.time() -- Update on successful call
--- timer.started will be false if it's ended (because single_shot)
if timer.started then return end
timer:again()
f(...)
end
end
Expand Down

0 comments on commit 39e8f84

Please sign in to comment.