Question

I have this code working, but I'd like to improve it:

var c = canvas.getContext("2d"); 
//this is called as an object method I created
var animar = function () {
   var obj = this;//saves the object that called it to later access to its properties
   var counter= 0;
   var animacion = setInterval(function(){
            c.save()
            c.clearRect(0, 0, canvas.width, canvas.height);
            c.rotate(0.1*counter);
            obj.pintar();
            c.restore();
            counter++;

   }, 50);
}

I'd like to use a outter function for posible future use but when I change the code I have, there is a hoisting problem and I don't know how to get the counter inside the rotar() function without overwriting it all the time:

var animar = function () {
    var obj = this;
    var counter= 0;
    var animacion = setInterval(function(){
        rotar(obj)
    }, 50);
}

function rotar (obj) {
    c.save()
    c.clearRect(0, 0, canvas.width, canvas.height);
    c.rotate(0.1*counter);
    obj.pintar();
    c.restore();
    counter++;
}

I get that the first one works because they are nested, while in the second example isn't. How can I have a counter for the setInterval WITHOUT USING A GLOBAL VARIABLE? (I mean... if I call it a second time, it will not start in 0. If I set it to be 0 in the animar() function, it would work, but then I'd need to set it to 0 in every function that uses a counter or using counters with diferent names. This two posibilities don't sound good.) Thanks

Was it helpful?

Solution

You just need to put var counter = 0 outside the functions:

var counter;
var animar = function () {
    var obj = this;
    counter = 0; // reset every time before 'animacion'...
    var animacion = setInterval(function(){
        rotar(obj)
    }, 50);
}
function rotar (obj) {
    c.save()
    c.clearRect(0, 0, canvas.width, canvas.height);
    c.rotate(0.1*contador);
    obj.pintar();
    c.restore();
    counter++;
}

Alternatively, if you don't want a global variable, you can follow Walter's answer, or do this:

var animar = function () {
    var obj = this;
    var counter = 0; // new variable every time animar() is called
    var animacion = setInterval(function(){
        rotar(obj, counter);
        counter++;
    }, 50);
}
function rotar (obj, counter) {
    c.save()
    c.clearRect(0, 0, canvas.width, canvas.height);
    c.rotate(0.1*contador);
    obj.pintar();
    c.restore();
}

OTHER TIPS

make counter scoped inside of your animar object:

var animar = function () {
    var obj = this;
    obj.counter= 0;
    var animacion = setInterval(function(){
        rotar(obj)
    }, 50);
}

function rotar (obj) {
    c.save()
    c.clearRect(0, 0, canvas.width, canvas.height);
    c.rotate(0.1*obj.counter);
    obj.pintar();
    c.restore();
    obj.counter++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top