javascript setInterval 动画循环不循环

javascript setInterval animation loop not looping

我知道这个有很多变体,但我不明白为什么这个不循环。它只运行一次 segmentConstruction。

        var timer;           
        timer = setInterval(segmentConstruction(multipointCoords,whaleTime), 1000);

        function segmentConstruction(multipointCoords,whaleTime){

            console.log(multipointCoords[0][0]);
            console.log(whaleTime[0][0]);
            console.log(i);

            if (i > 10) {
                clearInterval(timer);
            }
            else {
                i++;
                timer;
            };
        };

因为 setInterval(segmentConstruction(multipointCoords,whaleTime), 1000); 等同于:

var t = segmentConstruction(multipointCoords,whaleTime);
setInterval(t, 1000);

从 IE10 开始,您可以:

setInterval(segmentConstruction, 1000, multipointCoords, whaleTime);

你不应该以这种方式传递函数参数。

您可以在匿名函数中使用参数调用您的函数。
此解决方案适用于所有浏览器:

timer = setInterval(function() {
    segmentConstruction(multipointCoords,whaleTime);
}, 1000);

function segmentConstruction(coords, time)
{
    // ...
}

此方法仅用于函数不带参数:

timer = setInterval(segmentConstruction, 1000);

function segmentConstruction()
{
    // ...
}

这是因为当您启动间隔时,segmentConstruction 函数调用一次。 有两种修复方法:

  1. 像这样在 setInterval 构造中将 segmentConstruction 包装到闭包中:

    setInterval(function () {segmentConstruction(multipointCoords,whaleTime); }, 1000);

  2. 段构造应return闭包:

    function segmentConstruction(multipointCoords,whaleTime){
        return function () {
            console.log(multipointCoords[0][0]);
            console.log(whaleTime[0][0]);
            console.log(i);
    
            if (i > 10) {
                clearInterval(timer);
            }
            else {
                i++;
                timer;
            }
        };
    }