refactor(utils): switch debounce() and throttle() to use vim.defer_fn()
vim.defer_fn() does exactly what half of Utils.debounce() and Utils.throttle() code does, so use it. While at it add function annotations.
This commit is contained in:
@@ -736,6 +736,10 @@ function M.trim_line_numbers(content)
|
|||||||
return vim.iter(content):map(function(line) return (line:gsub("^L%d+: ", "")) end):totable()
|
return vim.iter(content):map(function(line) return (line:gsub("^L%d+: ", "")) end):totable()
|
||||||
end
|
end
|
||||||
|
|
||||||
|
---Debounce a function call
|
||||||
|
---@param func fun(...) function to debounce
|
||||||
|
---@param delay integer delay in milliseconds
|
||||||
|
---@return fun(...): uv.uv_timer_t debounced function
|
||||||
function M.debounce(func, delay)
|
function M.debounce(func, delay)
|
||||||
local timer = nil
|
local timer = nil
|
||||||
|
|
||||||
@@ -747,35 +751,31 @@ function M.debounce(func, delay)
|
|||||||
timer:close()
|
timer:close()
|
||||||
end
|
end
|
||||||
|
|
||||||
timer = vim.loop.new_timer()
|
timer = vim.defer_fn(function()
|
||||||
if not timer then return end
|
func(unpack(args))
|
||||||
|
|
||||||
timer:start(delay, 0, function()
|
|
||||||
vim.schedule(function() func(unpack(args)) end)
|
|
||||||
timer:close()
|
|
||||||
timer = nil
|
timer = nil
|
||||||
end)
|
end, delay)
|
||||||
|
|
||||||
return timer
|
return timer
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
---Throttle a function call
|
||||||
|
---@param func fun(...) function to throttle
|
||||||
|
---@param delay integer delay in milliseconds
|
||||||
|
---@return fun(...): nil throttled function
|
||||||
function M.throttle(func, delay)
|
function M.throttle(func, delay)
|
||||||
local timer = nil
|
local timer = nil
|
||||||
local args
|
|
||||||
|
|
||||||
return function(...)
|
return function(...)
|
||||||
args = { ... }
|
|
||||||
|
|
||||||
if timer then return end
|
if timer then return end
|
||||||
|
|
||||||
timer = vim.loop.new_timer()
|
local args = { ... }
|
||||||
if not timer then return end
|
|
||||||
timer:start(delay, 0, function()
|
timer = vim.defer_fn(function()
|
||||||
vim.schedule(function() func(unpack(args)) end)
|
func(unpack(args))
|
||||||
timer:close()
|
|
||||||
timer = nil
|
timer = nil
|
||||||
end)
|
end, delay)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user