Smart Ticker Pausing in CreateJS

Mar 19
2013

I’ve been working on some projects lately using the CreateJS libraries. It takes some getting used to, but overall the API works well for someone coming from an ActionScript background.

One of the projects I’ve been working on is more of an activity than a game. One of the optimizations I make in the activity is to pause the CreateJs Ticker when there are no active animations. This way the I don’t waste cycles updating elements when the app is static.

My first approach to this was simply to unpause the ticker before I started a tween, and in the tween complete handler, pause the ticker again. This worked fine until I started to have more than one tween active at the same time. I could try to keep track of which tween would finish first and then not repause the ticker until the second one had finished. That gets messy fast though, and for some things it’s not consistent.

I needed a way to keep track of how many elements were currently tweening and to only repause the ticker when all those elements were done.

What I came up with is a retain count method to keep track of how many tweens are currently requesting for the ticker to be active. This is similar to the way memory is managed in iOS.

I start in the app setup by creating a retainCount property on the ticker and setting it to 0.

createjs.Ticker.retainCount = 0;

I then create two functions called pauseTicker and unPauseTicker. These are global functions in my app namespace, so I can call them from anywhere.

pauseTicker = function(){
    createjs.Ticker.retainCount--;
    if(createjs.Ticker.retainCount < 1){
        createjs.Ticker.setPaused(true);
        createjs.Ticker.retainCount = 0;
    }
};

unPauseTicker = function(){
    createjs.Ticker.retainCount++;
    createjs.Ticker.setPaused(false);
};

Now anywhere in my app where I want tween an element I call unPauseTicker and pauseTicker instead of using Ticker.setPaused() directly.

It works by keeping a count of how many requests have been to unpause and pause the ticker. Each call to unPauseTicker increments the count, and each call to pauseTicker decrements it. When the count reaches 0 again the ticker actually gets paused using setPaused.

This way I can start as many simultaneous and overlapping tweens as I want and know that when the last one completes the ticker will repause itself. So far it seems to be working pretty well for my needs.