1.0.4 • Published 4 years ago

typed-loop v1.0.4

Weekly downloads
1
License
ISC
Repository
github
Last release
4 years ago

typed-loop

A loop class to enable flexible intervals for visual experiments and games. It provides delta time in various formats and uses requestAnimationFrame for the timeouts. It's possible to use setTimeout with given targetDeltaTime.

How to use

Install by issuing npm i typed-loop.

This module exports a Loop class, DeltaTimeFormat enum and LoopParameters interface.

import { Loop } from 'typed-loop';

const loop = new Loop({
  onTick(deltaTime) {
    console.log(deltaTime)
  }
});

API

interface LoopParameters

NameRequired?TypeDefault valueDescription
onTickYes(deltaTime: number) => anyundefinedcallback function to be called on every tick of the loop
deltaTimeFormatNo'relative' | 'milliseconds' | 'seconds''milliseconds'how the delta time should be formatted
deltaTimeLimitNonumber | undefinedundefinedmaximum delta time in milliseconds
startWithoutDelayNobooleanfalseshould the callback be called immediately
targetTimeoutNonumber | undefinedundefinedtarget timeout, tick on every frame not guaranteed if set

class Loop(config: LoopParameters)

import { Loop, LoopParameters, DeltaTimeFormat } from 'typed-loop';

const conf: LoopParameters = {
  onTick: (deltaTime) => {
    console.log(`Last tick happened ${deltaTime} seconds ago`);
  },
  startWithoutDelay: true,
  deltaTimeFormat: DeltaTimeFormat.SECONDS
};

const loop = new Loop(config).start();

// --> Last tick happened 0.017 seconds ago
// --> Last tick happened 0.016 seconds ago

setTimeout(() => {
  loop.stop();
}, 36);

Methods

#start(): self

Starts the loop.

#stop(): void

Stops the loop.

Additional info

requestAnimationFrame vs setTimeout

requestAnimationFrame schedules a function to be called right before the next screen repaint. Most commonly the repaint occurs every 16ms resulting 60 frames / second (FPS). setTimeout schedules function to be called after given milliseconds, however, it seems that the delay is always at least around 4ms even with timeout of 0.

Due to this all loops that animate visible entities will benefit using requestAnimationFrame as excess repaints (high FPS) between screen repaints will not be visible to the users and skipped screen repaints (low FPS) result in jumps and lag.

Why delta time?

Screen refresh rate is not same for all devices and furthermore the refresh rate varies a bit, typically around +-5ms based on load of the machine among other factors.

When animating movement on sceen (e.g. games and animations) the previously mentioned inaccuracy of FPS causes visible jumping and lagging. This can be mitigated by applying the actual duration of previous frame time when calculating new position for the animated elements.

Example - laggy

Without compensating the variance of FPS.

let x = 0;

function loop() {
  x += 5;
  repaint(x); // Arbitrary function to repaint to updated position
  requestAnimationFrame(loop);
}

Example - less laggy

Applying FPS variance compensation with delta time.

let x = 0;

new Loop({
  deltaTimeFormat: DeltaTimeFormat.RELATIVE,
  onTick(deltaTime => {
    x += 5 * deltaTime;
    repaint(x); // Arbitrary function to repaint to updated position
  })
}).start();

How to contribute

Open issue or make a PR if it's a simple patch or quick feature.