2013-01-31 126 views
0

如果我有一個函數,如下所示:打破一系列超時命令?

function x() 
{ 
    animate(a, 2000); 
    animate(b, 3000); 
    animate(c, 4000); 
} 

凡 - A,B &Ç - 是表示頁面上的元素的變量,和數量是傳遞到使用它作爲一個動畫()函數中的參數對於超時的持續時間值,就像這樣:

function animate(src, dur) 
{ 
    setTimeout(function() { 
     src.style.opacity = 1; 
    }, dur); 
} 

一切到目前爲止是好的,但如果我想打出來的動畫循環的能力,我怎麼做呢?將clearTimeout()是我正在尋找什麼?

+0

我沒有看到動畫循環,我只看到三個獨立的超時。 – Bergi

回答

1

已分配超時值的變量可能會傳遞給clearTimeout函數,該函數將停止該函數。您可以將這些變量存儲在數組中,並通過迭代該數組並將超時值傳遞給clearTimeout函數來輕鬆清除所有超時。

var timeouts = []; 

/* Save timeouts into a variable and push to an array */ 
function animate(src, dur) 
{ 
    var timeout = setTimeout(function() { 
     src.style.opacity = 1; 
    }, dur); 
    timeouts.push(timeout); 
} 

/** Clear all timeouts**/ 
function clearTimeouts(){ 
    for(var i = 0; i < timeouts.length; i++){ 
    clearTimeout(timeouts[i]); 
    } 
} 

//Create timeouts 
x(); 
//Invoke clearTimeouts 
clearTimeouts(); 
+0

這看起來像一個有趣的代碼,但請原諒我在這裏缺乏理解 - 什麼是timeouts.push(超時),我沒有得到'推'部分。這是在第一行創建的數組對象的通用方法嗎? – Abhishek

+1

@Abhishek:['push'](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push)將一個項目推送到一個數組上 – Bergi

0

是,clearTimeout()是正確的方式去:

function animate(src, dur) 
{ 
    return setTimeout(function() { 
     src.style.opacity = 1; 
    }, dur); 
} 

,並保存返回的標識符:

function x() 
{ 
    var aId = animate(a, 2000); 
    var bId = animate(b, 3000); 
    var cId = animate(c, 4000); 
} 

以後您只需撥打clearTimeout(aId)或任何你的願望。順便說一句,你的代碼中沒有循環,setTimeout()只執行一次,如同暗示爲setInterval()

+0

是的,我使用超時,因爲這些是一個動畫,我不想讓他們循環...但是,無論如何謝謝你指出它:) :) – Abhishek