Skip to content

Commit

Permalink
feat(util): throttle
Browse files Browse the repository at this point in the history
  • Loading branch information
folke committed Dec 16, 2024
1 parent 3123e6e commit 737980d
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion lua/snacks/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ M.meta = {
desc = "Utility functions for Snacks _(library)_",
}

local uv = vim.uv or vim.loop

---@alias snacks.util.hl table<string, string|vim.api.keyset.highlight>

local hl_groups = {} ---@type table<string, vim.api.keyset.highlight>
Expand Down Expand Up @@ -157,7 +159,7 @@ function M.redraw(win)
end
end

local mod_timer = assert((vim.uv or vim.loop).new_timer())
local mod_timer = assert(uv.new_timer())
local mod_cb = {} ---@type table<string, fun(modname:string)[]>

---@return boolean waiting
Expand Down Expand Up @@ -234,4 +236,27 @@ function M.on_key(key, cb)
end)
end

---@generic T
---@param fn T
---@param opts? {ms?:number}
---@return T
function M.throttle(fn, opts)
local timer, trailing, ms = assert(uv.new_timer()), false, opts and opts.ms or 20
return function()
if timer:is_active() then
trailing = true
return
end
trailing = false
if vim.in_fast_event() then
vim.schedule(fn)
else
fn()
end
timer:start(ms, 0, function()
return trailing and vim.schedule(fn)
end)
end
end

return M

0 comments on commit 737980d

Please sign in to comment.