Skip to content

Commit

Permalink
fix: throttler
Browse files Browse the repository at this point in the history
  • Loading branch information
apollo1321 committed Dec 4, 2024
1 parent 1d12cbb commit 01ca79f
Showing 1 changed file with 40 additions and 13 deletions.
53 changes: 40 additions & 13 deletions lua/treesitter-context.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,52 @@ local all_contexts = {}
--- @param ms? number
--- @return F
local function throttle_by_id(f, ms)
ms = ms or 200
ms = ms or 150

local State = {
Scheduled = {},
Running = {},
Throttled = {},
}

local timers = {} --- @type table<any,uv.uv_timer_t>
local state = {} --- @type table<any,table>
local waiting = {} --- @type table<any,boolean>
return function(id)

local schedule = function(id, wrapper)
state[id] = State.Scheduled
vim.schedule_wrap(wrapper)(id, wrapper)
end

local on_throttle_finish = function (id, wrapper)
if waiting[id] == nil then
timers[id] = nil
state[id] = nil
return
end
waiting[id] = nil
schedule(id, wrapper)
end

local wrapper = function(id, wrapper)
assert(state[id] == State.Scheduled)
state[id] = State.Running
f(id)
assert(state[id] == State.Running)
state[id] = State.Throttled

if timers[id] == nil then
timers[id] = assert(vim.loop.new_timer())
else
waiting[id] = true
return
end
timers[id]:start(ms, 0, function() on_throttle_finish(id, wrapper) end)
end

f(id) -- first call, execute immediately
timers[id]:start(ms, 0, function()
if waiting[id] then
f(id) -- only execute if there are calls waiting
end
waiting[id] = nil
timers[id] = nil
end)
return function(id)
if state[id] == nil then
schedule(id, wrapper)
return
end
waiting[id] = true
end
end

Expand Down

0 comments on commit 01ca79f

Please sign in to comment.