tempse
tempse

Reputation: 51

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.

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

Both setTimeout 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 !

Upvotes: 1

Views: 834

Answers (2)

Tibrogargan
Tibrogargan

Reputation: 4603

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

... and I just blew 15 minutes on this, lol:

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

Upvotes: 2

devitall
devitall

Reputation: 56

How about moving the image up immediately when you call bounce and then returning it to the original position after a timeout?

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

Upvotes: 0

Related Questions