steploop
v1.0.1
Published
a foundation for building loops that execute at a consistent, specified rate
Maintainers
Readme
About steploop
steploop is a fully-featured main-loop written in TypeScript with no additional dependencies. It provides a strong foundation for building loops that execute at a consistent, specified rate, inspired by game engine main-loops like Godot's MainLoop or Unity's Update() loop.
steploop provides a structured lifecycle with methods that can be overridden to implement custom behavior.
The StepLoop class manages the timing and execution flow, supporting both fixed-step updates via setTimeout() and smoother, display-synchronized updates using window.requestAnimationFrame().
Install
Install steploop via NPM:
npm i steploopImport the StepLoop class in your TypeScript or JavaScript file:
import { StepLoop } from "steploop";Basic Usage
To define a new loop, extend the StepLoop class and override its methods to implement custom behavior.
import { StepLoop } from "steploop";
class App extends StepLoop {
override initial(): void {
console.log("Loop starting");
}
override step(): void {
console.log(`Executing step: ${this.get_step()}`);
}
override final(): void {
console.log("Loop finished");
}
}
// Create a new loop that runs at 60 steps-per-second for 100 steps
const app = new App(60, 100);
app.start();To see a StepLoop in action and play with execution, check out the demo page or the demo code.
Lifecycle
The StepLoop class executes in three distinct stages, with hooks that can be overridden to add custom logic:
- Initialization: Runs once at the beginning of the loop
initial(): Runs once at the beginning of the loop.
- Looping: The core of the loop, which repeatedly executes the following sequence:
background(): Runs asynchronously at the beginning of each step.before(): Runs before the mainstep()method.step(): The main update function for your loop.after(): Runs after thestep()method.
- Termination: Runs once when the loop ends, either by reaching the end of its lifespan or being manually stopped
final(): Runs once when the loop ends.
The loop can run indefinitely or for a set number of steps, and its execution can be precisely controlled, allowing it to be paused, resumed, and dynamically modified at runtime.
Reference
For full documentation of the module and its methods, please see the Documentation page.
License
steploop is released under the MIT license. For more information, see the repository's LICENSE file.
