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

僤鯓⒐⒋嵵緔 提交于 2019-12-11 13:19:12

问题


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 !


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/37125419/js-using-a-settimeout-inside-a-setinterval-the-settimeout-has-no-effect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!