HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Basic animation in Typescript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
typescriptanimationbasic

Problem

I decided to play around with doing my own super-basic animation. For a previous Javascript project, I needed the ability to flash an element. The code below is the result of me attempting to generalize the main animation loop function, and learn Typescript at the same time.

What I'm looking for suggestions on:

-
The name of my main animation loop (doOverEveryThen). It's terrible, but basically describes what the function does. Any suggestions here would be appreciated.

-
For the defaultable parameters, I had two options:

  • Use the "JavaScript way", but putting something like thenF = thenF || function(){} at the start of the function.



  • Opt for the Typescript way of default parameters.



Going with Typescript's default parameters seemed like the better way to go, but it also bulked up an already long line.

-
The first function, my "animation loop" is the heart of the two animations. For the job it needs to do, is it optimal? Can it be improved at all in terms of efficiency or neatness?

-
This is the first code I've written in Typescript. Any suggestions specific to the language would be appreciated.

What I don't need suggestions on:

  • I know I could have used jQuery for a much better result. That would have defeated the purpose though.



At the bottom, I put a Stack Snippet that uses the JavaScript that the Typescript compiles into.

```
/**
* Calls the frameAction function once per frame, then executes the callback.
*
* @param durationMS How long it should run for
* @param frameAction A function to be executed once per frame
* @param thenF The callback to run after it completes
* @param frameDelayMS The delay between frames
*/
function doOverEveryThen(durationMS: number, frameAction: (percentageComplete: number) => void, thenF: () => void = function(){}, frameDelayMS: number = 33) {
let percPerMS = 1 / durationMS;
let changePerFrame = percPerMS * frameDelayMS;

let currentPerc = 0;
let animationInterval = setInterval(function

Solution

My eye is drawn to the number of parameters in your main animation loop function. I'd try to reduce that.

Since this function is essentially chaining callback functions and inserting delays, the opportunity I see is to use promises to more elegantly chain the callbacks (readability is one sure benefit).

Context

StackExchange Code Review Q#124634, answer score: 3

Revisions (0)

No revisions yet.