2012-05-31 34 views
0

什麼是寫這個更好的方法:優化的JavaScript的setTimeout

setTimeout(function() { 
    $('#clock').animate({ 
     'marginTop': '-20px' 
    }, 'slow', $.bez(bezierEasing)); 
}, 100); 
setTimeout(function() { 
    $('#submit').animate({ 
     'top': '-5px' 
    }, 500, $.bez(bezierEasing)); 
}, 200); 
setTimeout(function() { 
    $('#details').animate({ 
     'top': '-200px' 
    }, 500, $.bez(bezierEasing)); 
}, 300); 
setTimeout(function() { 
    $('#details').animate({ 
     'top': '19px' 
    }, 100, $.bez(bezierEasing)); 
}, 600); 
+0

不知道爲什麼我下投票? – user1381806

+2

我並沒有冷靜下來,而是「幫助我做出更好的」問題,而沒有對您遇到的問題或者您認爲很尷尬的部分或類似的東西進行有用的描述,那麼這些問題不會爲人們提供很多方向試圖幫助。你的代碼有什麼東西讓你希望它「更好」? – Pointy

回答

2

創建一個函數:

// adjust your function accordingly... 
function animateIt(selector, speed, top) { 
    setTimeout(function() { 
    $(selector).animate({ 
    'top': top 
    }, speed, $.bez(bezierEasing)); 
    }, 600);  
} 
+0

+1優秀,優化。 – thecodeparadox

+0

可能有一個時間參數,而不是600的值。 – hkutluay

+0

@hkutluay:是的,這就是爲什麼我寫了'相應地調整你的功能...'。這應該很容易:) – Sarfraz

1

而不是使用一些奇怪的超時鏈的,爲什麼你不使用TimelineMax從使用GreenSock .COM。

它更先進,更方便使用。

1

僅僅拋出我的版本...

function animateEl(selector, css, speed, timer) { 
    var tmp = parseInt(speed, 10); 
    if (!isNaN(tmp)) { 
     speed = tmp; 
    } 
    return setTimeout(function() { 
     $(selector).animate(css, speed, $.bez(bezierEasing) 
    }, timer); 
} 

animateEl('#clock', {'marginTop': '-20px' }, 'slow', 100); 
animateEl('#submit', { 'top': '-5px' }, 500, , 200); 
animateEl('#details', { 'top': '-200px' }, 500, 300); 
animateEl('#details', { 'top': '19px' }, 100, 600); 
+0

謝謝你! – user1381806