unimonkiez / self-adjusting-interval

setInterval which works on browser, Node and React Native, like it should have
21 stars 0 forks source link

Self adjusting interval

npm versionBuild Status

Introdution

javascript's setInterval and setTimeout are lacking when trying to build an accurate timer, furthermore, javascript's nature of being idle can throw off your timers even more!

Here comes self adjusting timers to the rescue!

Tested on -

How does it work

Javascript is a scripting language with runs on one process, due to that both setInterval and setTimeout are not accurate because the process can be busy with other stuff.

Setting a traditional interval will very quickly will prove itself inaccurate, in this picture you can see the offset which is produced by these functions

  setInterval(() => { /* Actually called late/early. */ }, 1000);

wrong

This library will calculate the delta between callbacks and will aim to hit your expectation every time, very much like a game stepping machanism (game time accumalation is anotehr library I wrote for that)
right

Also, javascript can be paused on slowed down to a hault (for example when your user exits your react native app, switching between tabs, or even by rendering UI), so instead of running your callback bunch of times for every missed second, your callback gets to run once with a ticks parameter which tells how much to "tick" by
batch

Usage