2011-11-10 19 views
0

我在學習JavaScript,我的一個練習是將框從左向右移動。它在最初的幾個週期內工作良好,但隨後變得混亂,我不知道是什麼原因造成的。我嘗試從左向右移動框,然後再次移動,但在幾個週期後崩潰

function preparePage(){ 
     var box = document.getElementById("box"); 
     var leftPosition = 0; 
     box.style.position = "absolute"; 

     function animateRight(){ 
      leftPosition += 1; 
      if (leftPosition<=300){ 
        box.style.left = leftPosition+"px"; 
      } else { 
       console.log("leftPosition = ",leftPosition); 
       clearInterval(intervalRight); 
       intervalLeft = setInterval(animateLeft, 20); 
       } 
     } 

     function animateLeft(){ 
      if (leftPosition>=0){ 
       leftPosition -=1; 
       box.style.left = leftPosition+"px"; 
      } else { 
       console.log("leftPosition =", leftPosition); 
       clearInterval(intervalLeft); 
       setInterval(animateRight,20); 
      } 
     } 

     intervalRight = setInterval(animateRight,20); 
    } 



    window.onload = function(){ 
     preparePage(); 
    } 
+0

定義 「它就會變得混亂」。 – Toomai

+0

[這是完整的代碼](http://pastebin.com/e9keWpEV)。起初,當它向左移動時它開始移動得更快,然後它從一側跳到另一側,遠遠超過預期的300像素。 – pumpalarumpa

回答

1

你忘了把間隔的句柄右移到變量中。當你第二次開始向左移動時,它不會停止當前的向右移動,它會嘗試再次停止第一個時間間隔。

更改此:

setInterval(animateRight,20); 

到:

intervalRight = setInterval(animateRight,20); 
+0

謝謝!它現在完美運行,但我承認我仍然不明白爲什麼它會這樣做......它在每個循環中向左移動得越來越快,並且最終開始從窗口的末端跳到另一個並導致我的瀏覽器崩潰。 – pumpalarumpa

+0

每當箱子開始向左移動時,您試圖停止不再存在的時間間隔,並開始另一個時間間隔。現在你有幾個時間間隔來爭奪盒子應該去的地方,並且一直開始更多的時間間隔,直到它超載瀏覽器。 – Guffa

+0

再次感謝,我想我現在明白了。我還發現,如果我把leftPosition + = 1;在if語句中,即使沒有設置句柄,它也能正常工作,儘管背景中有很多運行計時器(這對瀏覽器性能的影響並沒有像以前那樣大)。如果我把迭代放在if語句中,我可能根本就沒有發現丟失的句柄問題...... – pumpalarumpa

相關問題