2016-05-09 3 views
1

ランダムな画像を上に移動して元の位置に戻そうとしています。JS:setTimeout内でsetTimeoutを使用すると、setTimeoutは何の効果もありません。

<script> 

var looper = setInterval(animateAll, 2000, myArray); 
function animateAll(myArray) { 

    // Gets a random image ID 
    var randomId = myArray[Math.floor(Math.random()*myArray.length)]; 

    // Make that random icon bounce 
    bounce(randomId) ; 
} 

function bounce(randomId) { 
    var icon = document.getElementById(randomId) 

    var top = icon.offsetTop; 

    setTimeout (icon.style.top = top-20 + "px", 500) ; 
    setTimeout (icon.style.top = top + "px", 500) ; 
} 
</script> 

setTimeoutの両方の回線が正常に動作します。 1行だけで、画像は元の位置に戻らずに移動します。両方のラインでは、画像が全く動かない。恐らくそれぞれの間に遅延がないからです。

ありがとうございました!

+0

最初の引数に関数を渡す必要はありませんか? – PhilVarg

答えて

2

問題は、すぐにsetTimeoutコールでコードを実行していることです。あなたは効果的に「icon.style.top = whateverを500ミリ秒で設定した結果を実行する」と言っています...何もしません。

icon.style.top = top-20 + "px"; 
setTimeout (function() { icon.style.top = top + "px"; }, 500) ; 

を...と私は笑、これに15分を吹い:

代わりにこれを試してみてください

var steps = 7; 
var increment = (Math.PI)/steps; 
var bounceHeight = 20; 

function doStep(icon, start, major, minor, height) { 
    if (minor == steps) { 
     major--; 
     height /= 2; 
     minor = 0; 
     icon.style.top = start; 
    } 
    if (major < 0) { 
     return; 
    } 
    if (minor < steps) { 
     pos = Math.sin((minor + 1) * increment); 
     icon.style.top = (start - height * pos) + "px"; 
     setTimeout(function() { doStep(icon, start, major, minor + 1, height); }, 500/steps); 
    } 
} 

function bounce(randomId) { 
    var icon = document.getElementById(randomId) 

    var top = icon.offsetTop; 
    setTimeout (function() { doStep(icon, top, 3, 0, bounceHeight); }, 500/steps) ; 
} 
+0

それだけです。ありがとうございます – tempse

+0

@tempse新しいバージョンを試してください:) – Tibrogargan

+0

...残っている場合は、問題が残っています。 – Tibrogargan

0

どのようにバウンスを呼び出すときに、すぐに画像を上に移動し、その後帰国についてタイムアウト後に元の位置に移動しますか?

function bounce(randomId) { 
    var icon = document.getElementById(randomId) 

    var top = icon.offsetTop; 

    icon.style.top = top-20 + "px"; 
    setTimeout (icon.style.top = top + "px", 500) ; 
} 
関連する問題