Vim 8.0 で追加された機能 タイマー

Vim 8.0 ではついに Vim script にタイマー機能が追加されました!
この機能を使用することで処理をブロックしないで関数を呼び出すことが出来ます。

[基本的な使い方]

タイマーは timer_start() 関数を使用して任意の関数を n 時間後に呼び出す事が出来ます。

function! s:disp(timer)
    echo "callback"
endfunction

" 第一引数に時間、第二引数に呼び出す関数参照を渡す
" 1000ミリ秒後に s:disp をブロックしないで呼び出す
call timer_start(1000, function("s:disp"))

[タイマーを止める]

タイマーを止めたい場合、timer_start() が返した ID と timer_stop() を利用します。

" タイマーIDを受け取る
function! s:disp(timer)
    echo "callback"
endfunction

let s:id = timer_start(1000, function("s:disp"))

" ID のタイマーを止める
call timer_stop(s:id)

コールバック関数が受け取る timertimer_start() で生成された ID になります。 また、timer_stopall() ですべてのタイマーを止める事が出来ます。

[回数を指定する]

timer_start() の第三引数にリピートする回数を指定する事が出来ます。

let s:counter = { "value" : 0 }
function! s:counter.count(...)
    echo self.value
    let self.value += 1
endfunction

" 1000ms ごとに s:counter.count() を 3回呼び出す
call timer_start(1000, s:counter.count, { "repeat" : 3 })

また、-1 をすることでタイマーを止めるまで呼ばれ続けます。

let s:counter = { "value" : 0 }
function! s:counter.count(timer)
    echo self.value
    let self.value += 1

   " 5回呼ばれたら止める
    if self.value >= 5
        call timer_stop(a:timer)
    endif
endfunction

" 1000ms ごとに s:counter.count() を呼び出し続ける
call timer_start(1000, s:counter.count, { "repeat" : -1 })

かなり便利。