reloop v1.0.7
Reloop: A Small Simulation Loop Library
Reloop is a small library that provides a simple tick
/ draw
wrapper around the browser's requestAnimationFrame
API.
Reloop deals with updating your simulation at a constant rate, requesting draw frames from the browser, and even determines how much time is left between two simulation frames when rendering, so that you can draw using interpolation (if you wish).
Setup
You can install reloop using npm
or similar:
$ npm install reloop
Reloop is built as a UMD module, so it should work with AMD, CommonJS, or via a <script>
tag.
You can also load reloop via the jsDelivr CDN.
Usage
Using reloop is extremely simple. First, load reloop using your mechanism of choice:
const reloop = require('reloop');
Next, create a new loop object:
const loop = new reloop();
Optionally, you can set the loop's simulation rate, or the number of frames that reloop should try to simulate each second:
loop.rate(30.0);
Next, you can register three callbacks: load
, which triggers whenever the loop is started; tick
, which triggers at a fixed rate (the simultion rate); and draw
, which triggers whenever the browser gives us a draw frame:
loop
.load(function() {
// Your setup code goes here.
})
.tick(function(dt) {
// Your simulation update code goes here.
})
.draw(function(lerp) {
// Your rendering code goes here.
});
Note that all public reloop methods support chaining.
Finally, start the loop:
loop.loop();
Additionally, you may want to set up the loop to stop in certain cases, such as when the browser tab loses focus:
document.addEventListener('visibilitychange', function() {
if(document.hidden) {
loop.stop();
} else {
loop.loop();
}
});
You can have as many loops running concurrently as your browser can support. All loop state is captured inside of the reloop
object.
Example
See the example/
folder for a working demo program. You can run it by executing the following command in your shell:
$ npx webpack-dev-server
And then navigating to localhost:8080
in your browser. If everything works, you should see a slowly orbiting blue rectangle.
Building From Source
Clone or download the repository, then grab the dev dependencies:
$ npm install
Next, run webpack
, either in dev
or opt
mode:
$ npx webpack --env.opt # minified build
$ npx webpack --env.dev # non-minified build
Tests
Reloop has a small test suite implemented using Mocha & Chai. To run it, issue the following command:
$ npm test
If everything passes, you should see a bunch of green check marks.
License
Reloop is available under the ISC license.