JavaScript 动画错误 "pos" 元素每次迭代的变量

JavaScript animation wrong "pos" variable of an element with each iteration

下面JavaScript中包含云图的元素的动画到底有什么逻辑错误?我认为 "pos" 变量似乎在每次迭代中都偏离了方向,我无法弄清楚每次迭代云图像的运动如何变得越来越疯狂。

//CSS:
#container{
               background-color : #defffc;
               width : 100%;
               height : 100%;
               position : relative;
            }

#clouds{
            position : absolute;
            width : 300px;
            height : 200px;
            opacity : 0.3;
        }

//Body: 
<p><button type = "button" onclick = "animateCloud()">Move Cloud</button></p>
    <div id = "container">
        <div id = "cloudy">
            <img src ="cloudy.png" id = "clouds"></img>
        </div>
    </div>

//Script: 
<script>
        function animateCloud(){
            var pos = 0;
            var cloudElement = document.getElementById("clouds");
            var id = setInterval(motion, 5);

            function motion(){
                if(pos==1000){
                    //clearInterval(id);
                    id = setInterval(remotion, 5, pos);
                }
                else{
                        pos++;
                        cloudElement.style.left = pos + 'px';
                        cloudElement.style.right = pos + 'px';
                    }
                }

                function remotion(){
                alert(pos);
                    if(pos==0){
                            id = setInterval(motion, 5, pos);
                    }
                    else{
                            pos--;
                            cloudElement.style.right = pos + 'px';
                            cloudElement.style.left = pos + 'px';
                    }
                }
            }
</script>

通过使用 setInterval,您告诉 JavaScript 每 n 毫秒重复一次该函数,因此使用间隔调用函数创建更多间隔实际上是更频繁地调用您的位置变化。

我建议您查看 setTimeout() over setInterval() 以确保您没有重复创建更多间隔。

编辑:再次查看您的代码后,保留 clearInterval() 并记得将其也放入您的 remotion 基本案例中;否则你将开始像我上面提到的那样以指数方式创建更多间隔。