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

How to optimize this HTML5 animation?

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

Problem

I'm just learning the basics of animating with Javascript and HTML5. I'm trying to create this scrolling logos element for my site, and I'm pretty sure that my code is very inefficient. Can anyone give me any tips on how to do a better job of what I'm trying to do here?

http://jsbin.com/anagug/1/edit

Thanks!

EDIT: Here is the code:

var ctx;
        var count = 0;
        var xpos;
        var ypos;
        var revealTimer;

        var img = new Image();
        img.src = "http://www.firewalkcreative.com/2012/images/logos_1.png";

        function switchImage(){

            xpos = count * 150;
            ypos = 0;

            count++;
            ctx.globalAlpha = 0.1;
            revealTimer = setInterval(revealImage,100);

            if(count == 5)
                count = 0;

        }

        function revealImage() {
            ctx.drawImage(img, 0, 0, 840, 90, xpos, count, 840, 90);
            ctx.drawImage(img, 0, 0, 840, 90, xpos-900, 0, 840, 90);
            ctx.save();
            ctx.globalAlpha += 0.1;
            if (ctx.globalAlpha >= 1.0)
                clearInterval(revealTimer);
            ctx.restore();
        }

        function init() {

            ctx = document.getElementById("canvas").getContext("2d");
            setInterval(switchImage,3000);
        }

Solution

Always do a clearInterval() before doing a new setInterval() on the same variable. Doesn't matter if it has been cleared or not.

e.g.

clearInterval(revealImage);
revealTimer = setInterval(revealImage,100);


You're code has a bug where the revealTimer is being reset before being cleared.

Why do you need to reset it?

function init() {   
    ctx = document.getElementById("canvas").getContext("2d");
    setInterval(switchImage,3000);
    setInterval(revealImage,100);
}


Should work just as well.

Code Snippets

clearInterval(revealImage);
revealTimer = setInterval(revealImage,100);
function init() {   
    ctx = document.getElementById("canvas").getContext("2d");
    setInterval(switchImage,3000);
    setInterval(revealImage,100);
}

Context

StackExchange Code Review Q#14734, answer score: 2

Revisions (0)

No revisions yet.