Skip to content

Commit 8ebcf62

Browse files
apollo1321lewis6991
authored andcommitted
fix: throttler
1 parent 858c0e4 commit 8ebcf62

File tree

1 file changed

+40
-14
lines changed

1 file changed

+40
-14
lines changed

lua/treesitter-context.lua

Lines changed: 40 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,25 +15,51 @@ local all_contexts = {}
1515
--- @param ms? number
1616
--- @return F
1717
local function throttle_by_id(f, ms)
18-
ms = ms or 200
18+
ms = ms or 150
19+
1920
local timers = {} --- @type table<any,uv.uv_timer_t>
21+
local state = {} --- @type table<any,string>
2022
local waiting = {} --- @type table<any,boolean>
21-
return function(id)
23+
24+
local schedule = function(id, wrapper)
25+
state[id] = "scheduled"
26+
vim.schedule_wrap(wrapper)(id, wrapper)
27+
end
28+
29+
local on_throttle_finish = function(id, wrapper)
30+
assert(state[id] == "throttled")
31+
if waiting[id] == nil then
32+
timers[id] = nil
33+
state[id] = nil
34+
return
35+
end
36+
waiting[id] = nil
37+
schedule(id, wrapper)
38+
end
39+
40+
local wrapper = function(id, wrapper)
41+
assert(state[id] == "scheduled")
42+
state[id] = "running"
43+
f(id)
44+
assert(state[id] == "running")
45+
state[id] = "throttled"
46+
2247
if timers[id] == nil then
2348
timers[id] = assert(vim.loop.new_timer())
24-
else
25-
waiting[id] = true
26-
return
2749
end
50+
timers[id]:start(ms, 0, function() on_throttle_finish(id, wrapper) end)
51+
end
2852

29-
f(id) -- first call, execute immediately
30-
timers[id]:start(ms, 0, function()
31-
if waiting[id] then
32-
f(id) -- only execute if there are calls waiting
33-
end
34-
waiting[id] = nil
35-
timers[id] = nil
36-
end)
53+
return function(id)
54+
if state[id] == nil then
55+
schedule(id, wrapper)
56+
return
57+
end
58+
-- Don't set 'waiting' for 'scheduled' state since the callback is about to start.
59+
-- Consequently, there is no need to run it again after throttling is completed.
60+
if state[id] ~= "scheduled" then
61+
waiting[id] = true
62+
end
3763
end
3864
end
3965

@@ -188,7 +214,7 @@ function M.enable()
188214
if config.multiwindow then
189215
autocmd({ 'WinClosed' }, close)
190216
else
191-
autocmd({ 'WinLeave', 'WinClosed' }, close)
217+
autocmd({ 'BufLeave', 'WinLeave', 'WinClosed' }, close)
192218
end
193219

194220
autocmd('User', close, { pattern = 'SessionSavePre' })

0 commit comments

Comments
 (0)