JS:在 setInterval 中使用 setTimeout,setTimeout 无效 [英] JS : Using a setTimeout inside a setInterval, the setTimeout has no effect

查看:68
本文介绍了JS:在 setInterval 中使用 setTimeout,setTimeout 无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让随机图像向上移动然后返回到它们的原始位置.

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>   

两行 setTimeout 都可以正常工作.只有一行,图像将移动而不会返回其原始位置.对于两条线,图像根本不会移动,可能是因为每条线之间没有延迟.

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.

感谢您的帮助!

推荐答案

问题是您正在立即执行 setTimeout 调用中的代码.您实际上是在说在 500 毫秒内执行设置 icon.style.top = 任何 的结果"......什么也不做.

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.

试试这个:

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

...我刚刚吹了 15 分钟,哈哈:

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

这篇关于JS:在 setInterval 中使用 setTimeout,setTimeout 无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆