Search code examples
luaneovimneovim-plugin

Delaying Lua function so it runs after Neovim has successfully launched


I am building a Neovim plug-in with Lua that needs to run a command on the user's terminal to obtain system information. However, this function is causing Neovim to lag at startup. How can I schedule my function to run right after Neovim launches? Can I use vim.api to achieve this, or do I need to run the function asynchronously?

Currently, I import the function from a module and call it in the file where I define the user commands with vim.api.nvim_create_user_command.


Solution

  • The functions vim.schedule() and vim.schedule_wrap() may be what you are looking for. In short, they schedule a function to somewhere later in the event loop when one can access Neovim's API at a time that is "suitable" for Neovim itself.

    To delay the call of your function that is causing issues until 2 seconds after Neovim has started, you could do something like this:

    local function start_up_func()
        print("My start-up function here")
    end
    local function delayed_start_up_func()
        local timer = vim.loop.new_timer()
        -- Delay 2000ms and 0 means "do not repeat"
        timer:start(2000, 0, vim.schedule_wrap(start_up_func))
    end
    delayed_start_up_func()
    

    Alternatively, vim.schedule without the delay may resolve the issue(s):

    local function start_up_func()
        print("My start-up function here")
    end
    vim.schedule(start_up_func)
    

    For more information, have a look at the documentation with h:vim.schedule and h:vim.schedule_wrap. This video by TJ DeVries also provides a good overview of these functions and how they can be used.