JS:在setInterval中使用setTimeout,setTimeout无效

时间:2016-05-09 21:04:16

标签: javascript settimeout setinterval

我试图让随机图像向上移动然后返回原来的位置。

<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行都可以正常工作。只有一条线,图像将移动而不会返回其原始位置。对于这两行,图像根本不会移动,可能是因为每个图像之间没有延迟。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

问题是您正在执行setTimeout电话中的代码。你实际上是在说“执行在500毫秒内设置icon.style.top = whatever的结果”......它什么都不做。

请改为尝试:

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

答案 1 :(得分: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) ;
}