vimtricks.wiki Concise Vim tricks, one at a time.

How do I schedule a command to run after a delay in Vim?

Answer

:call timer_start(1000, {-> execute('echo "done"')})

Explanation

Vim's timer_start() function lets you schedule code to run after a specified delay in milliseconds. This enables deferred execution, polling, periodic updates, and other asynchronous patterns without blocking the editor.

How it works

  • timer_start({ms}, {callback}) — runs callback after ms milliseconds
  • The callback receives the timer ID as its argument
  • Returns a timer ID for later cancellation
  • timer_stop({id}) — cancels a scheduled timer

Example

" Run once after 2 seconds
:call timer_start(2000, {-> execute('echom "Hello!"')})

" Repeat every second (5 times)
:call timer_start(1000, {t -> execute('echom reltime()[0]')}, {'repeat': 5})

" Cancel a timer
:let tid = timer_start(5000, {-> execute('echo "late"')})
:call timer_stop(tid)

Tips

  • Use {'repeat': -1} for an indefinitely repeating timer
  • timer_info() lists all active timers
  • Timers run when Vim is idle — they won't interrupt typing
  • Useful for auto-save: timer_start(60000, {-> execute('silent! wall')}, {'repeat': -1})

Next

How do I return to normal mode from absolutely any mode in Vim?