Skip to content

Commit

Permalink
perf: added debounce for calculating context
Browse files Browse the repository at this point in the history
  • Loading branch information
folke committed May 10, 2023
1 parent f1179bd commit d46d931
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 23 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ require'treesitter-context'.setup{
-- When separator is set, the context will only show up when there are at least 2 lines above cursorline.
separator = nil,
zindex = 20, -- The Z-index of the context window
throttle_ms = 100, -- Throttle context updates in milliseconds
}
```

Expand Down
34 changes: 11 additions & 23 deletions lua/treesitter-context.lua
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ local defaultConfig = {
zindex = 20,
mode = 'cursor', -- Choices: 'cursor', 'topline'
separator = nil,
throttle_ms = 100, -- Throttle context updates in milliseconds
}

--- @type Config
Expand Down Expand Up @@ -392,31 +393,18 @@ end

--- @generic F: function
--- @param fn F
--- @param ms? number
--- @return F
local function throttle_fn(fn)
local recalc_after_cooldown = false
local cooling_down = false
local function wrapped()
if cooling_down then
recalc_after_cooldown = true
else
local start = vim.loop.hrtime()
fn()
local elapsed_ms = math.floor((vim.loop.hrtime() - start) / 1e6)
-- If this took < 2ms, we don't need a cooldown period. This prevents the context floats from flickering
if elapsed_ms > 2 then
cooling_down = true
vim.defer_fn(function()
cooling_down = false
if recalc_after_cooldown then
recalc_after_cooldown = false
wrapped()
end
end, 20)
end
end
local function throttle_fn(fn, ms)
ms = ms
local timer = vim.loop.new_timer()
return function(...)
local argv = vim.F.pack_len(...)
timer:start(ms, 0, function()
timer:stop()
vim.schedule_wrap(fn)(vim.F.unpack_len(argv))
end)
end
return wrapped
end

local function close()
Expand Down

0 comments on commit d46d931

Please sign in to comment.