這是我遇到的一件陌生事情。setTimeout在每次清除並重新調用時都會增加
基本上,我的網站上,有一羣紡紗形狀。首次調用時,每個旋轉形狀都會設置一個超時值,以使其旋轉。無論何時訪問者點擊網頁,這些形狀都會被清除並隨機生成。
問題在於,在第二次點擊時,它們旋轉得更快。第三次點擊甚至更快,第四次點擊它們旋轉得太快,以至於它們變得超級波動且不流暢。
當使用chrome:// flags FPS計數器觀看網站時,它將以偶數60 fps開始,然後等到第四次或第五次單擊時,它將跳到20到50 fps 。
代碼的縮寫部分如下:
//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);
}
此代碼可能有一些孔,但它的功能,問題是,之後的第五單擊它是波濤洶涌。
如果有人需要它,我可以添加更多代碼,但任何建議都會非常有幫助!
此代碼在哪裏?這是你實例化5次的對象的內部嗎?如果不是,你可能會重複使用所有形狀的't'變量,因此在調用destroy時只清除一個超時,因爲它們之間共享了't'。 – TheZ 2012-08-13 16:06:28
對我來說這似乎很好... – Polyov 2012-08-13 16:11:41
@TheZ你是絕對正確的!重寫了超時值,以便它包含5個對象,而不是爲每個對象設置一個新的超時值(這實際上是相同的超時變量)。我不知道如何表明您爲我回答了這個問題!但你做到了。 – Cabbibo 2012-08-14 21:34:36