tempse tempse - 5 months ago 12x
Javascript Question

JS : Using a setTimeout inside a setInterval, the setTimeout has no effect

I'm trying to make random images move upwards then return to their original position.


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) ;

lines work fine. With only one line, well the images will move without returning to their original position. With both lines, images don't move at all, probably because there's no delay between each.

Thanks for your help !


The problem is that you're executing the code in your setTimeout calls immediately. You're effectively saying "execute the result of setting the icon.style.top = whatever in 500 milliseconds" ... which does nothing.

Try this instead:

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