views:

47

answers:

2

I'm using the jQuery Rotate plugin, to animate the rotation of an image 90 degrees, and then stop the rotation.

My problem is that it won't stop rotating, even after calling clearInterval();

$(document).ready(function() {
    var finalAngle;
    var intval = setInterval(function func() 
    {
      $("#myimg").rotate(1);
      if(typeof func.angle == 'undefined' )
      {
           func.angle = 0;
      }

      func.angle += 1;

      finalAngle = func.angle;

    }, 1);

    if(finalAngle == 90)
    {
      clearInterval(intval);
    }
});

Basically all I'm doing is (statically) counting the angles, and once it hits 90, call the clearInterval function. I had to introduce another variable to store the count so that I could access it outside the setInterval function.

+3  A: 

It's easy. setInterval is called then the condition with finalAngle is evaluated and after one milisecond your rotating function is called. Therefore clearInterval is never called when finalAngle is 90.

This code should work for you:

$(document).ready(function() {

    var intval = setInterval(function func() 
    {
      $("#myimg").rotate(1);
      if(typeof func.angle == 'undefined' )
      {
           func.angle = 0;
      }

      func.angle += 1;

      if (func.angle == 90)
      {
        clearInterval(intval);
      }    
    }, 1);  
});
MartyIX
+1  A: 

The if statement is executed once. Try this?

$(document).ready(function() {
    var finalAngle;
    var intval = setInterval(function func() 
    {
      $("#myimg").rotate(1);
      if(typeof func.angle == 'undefined' )
      {
           func.angle = 0;
      }

      func.angle += 1;
      finalAngle = func.angle;
      if(finalAngle == 90)
      {
          clearInterval(intval);
      }


    }, 1);


});

Though I don't see why you can't just get away with...

$(document).ready(function() {
    var finalAngle=0;
    var intval = setInterval(function func() 
    {
      $("#myimg").rotate(1);

      finalAngle++;

      if(finalAngle == 90)
      {
          clearInterval(intval);
      }


    }, 1);


});
meder
Ugh... I'm such a dunce. I could have sworn that my if was INSIDE the set interval function. Thanks for the quick fix!
Chrys G.