This is one of the stranger things I have come across.
Basically, on my site, there are a bunch of spinning shapes. Each spinning shape sets a timeout when it is first called, to make it spin. Whenever a visitor clicks on the webpage, these shapes are cleared and randomly generated again.
The problem is that on the second click they are spinning a bit faster. on the third click even faster, and by the fourth click they are spinning so fast that they get super choppy and unfluid.
When watching the site with the chrome://flags FPS counter, it will start at an EVEN 60 fps, and then by the time it gets to the fourth or fifth click, it will be jumping between 20 and 50 fps.
an abbreviated section of the code is as follows:
//creates timeout variable OUTSIDE the timeout function, so it can be cleared
var t;
var speedRandom;
function getRandSpeed(){
var randomSpeed = (Math.random()*.01);
if (randomSpeed<=.001){
randomSpeed=.001;
}else if(randomSpeed>=.005){
randomSpeed=.005;
}
console.log(randomSpeed);
if (rightSpin==0){
speedRandom=randomSpeed;
rightSpin=1;
}else{
speedRandom=-randomSpeed;
rightSpin=0;
}
}
objs[whichImg].speed = speedRandom;
function rotateDrawing(whichImg){
//This is the function that centers the object
centerImg(whichImg);
//translates the object to the centered point (different for each frame)
objs[whichImg].ctx.translate(objs[whichImg].centeredX,objs[whichImg].centeredY);
//rotates to the correct angle
objs[whichImg].ctx.rotate(objs[whichImg].angle);
//draws the image
objs[whichImg].ctx.drawImage(objs[whichImg].image,0,0,objs[whichImg].height,objs[whichImg].width);
//adds to the angle of the object
objs[whichImg].angle+=objs[whichImg].speed;
t=setTimeout(function(){rotateDrawing(whichImg)},40);
}
//THE ABOVE CODE WILL BE EXECUTED FOR EVERY SHAPE (TOTAL AROUND 5)
//this is what is called when the screen is clicked
function destroy(){
functionThatClearsAllTheImages();
clearTimeout(t);
rotateDrawing(whichImg);
}
This code may have some holes in it, but it does function, the problem is that after the fifth click it is choppy.
I can add more code if anybody needs it, but any suggestions would be extraordinarily helpful!
The Problem was that each time I created a new object, the timeout lay within that creation code. This meant that the timeout was called 5 times, and when I cleared it, it was only cleared once.
In order to solve the problem, I created one timeout function that contained a loop within it that would rotate the shapes. This meant that everytime I had to clear it, it would essential clear the loop for all 5 shapes!