2012-10-30 22 views
0

我正在嘗試使用JavaScript爲頁面上的某些元素設置動畫效果(帶精靈的CSS動畫將不適用於我需要的操作)。在JavaScript中正確處理setTimeout

我目前正在做這樣的事情;

function animate_element(current_id) 
{ 
    var next_id = parseInt(current_id, 10) + 1; 
    $('#lighthouse')[0].src = '/element_' + next_id + '.png'; 

    if (next_id >= 8) { 
     next_id = 0; 
    }  

    setTimeout(function() { 
     animate_element(next_id); 
    }, 750); 
} 

技術上這個作品,但是這將是會做類似的事情在頁面上很多的動畫之一,我很擔心這是做這件事的方式效率極低。

我知道最好的做法是在調用setTimeout之前使用clearTimeout(),但我不知道如何記錄setTimeout並遞歸地將它傳遞給自身(如果這是有道理的!)。

任何有關這樣做的最佳實踐方式的指導將不勝感激。

+1

該代碼看起來沒問題。 'setTimeout'足夠「高效」,因爲它不會浪費任何CPU週期或捆綁其他任何東西。我會說你很好。 –

回答

2

「我知道最好的方法是調用setTimeout的前使用clearTimeout() ......」

對於你在做什麼,有沒有理由罵clearTimeout()因爲下一次調用永遠不會發生直到最後一個被執行。

在這一點上,沒有什麼可以清楚的。


FWIW,你的代碼可以縮短一點:

function animate_element(current_id) { 
    current_id = parseInt(current_id, 10); 

    function cycle() { 
     document.getElementById('lighthouse').src = '/element_' + current_id + '.png'; 
     current_id = ++current_id % 8 
     setTimeout(cycle, 750); 
    } 
} 

animate_element(0); 

或者,如果有幾個是一樣的,只是用不同的ID,就可以使其可重複使用這樣的:

function animate_element(id, idx) { 
    idx = parseInt(idx, 10); 

    function cycle() { 
     document.getElementById(id).src = '/element_' + idx + '.png'; 
     idx = ++idx % 8 
     setTimeout(cycle, 750); 
    } 
} 

animate_element('lighthouse', 0); 
1

沒有在你的代碼仔細一看,或者你在做什麼,但如果你想保留的價值,你可以關過變量:

var animate_element = (function(){ 

    var timer; 

    return function(current_id) 
    { 
     var next_id = parseInt(current_id, 10) + 1; 
     $('#lighthouse')[0].src = '/element_' + next_id + '.png'; 

     if (next_id >= 8) { 
      next_id = 0; 
     }  

     clearTimeout(timer); 
     timer = setTimeout(function() { 
      animate_element(next_id); 
     }, 750); 
    }; 

})(); 
1

我說setInterval將你的情況了setTimeout更好。

var current_id = 0; 

function animate_element() { 
    setInterval(function() { 
    var next_id = parseInt(current_id, 10) + 1; 
    $('#lighthouse')[0].src = '/element_' + next_id + '.png'; 

    if (next_id >= 8) { 
     next_id = 0; 
    } 

    current_id = next_id; 
    }, 750); 
} 
+0

這樣做的好處是什麼? – Toby

+1

如果您在每個超時結束時調用相同的函數,則實際上是在創建間隔。爲了避免清除和調用超時,你可以使用'setInterval()'函數來完成這個工作。 –