且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无限期地重复一个函数,***不使用setInterval()

更新时间:2023-08-31 21:54:28

一个简单的解决方案是从动画最后一步的完成回调"中进行伪递归循环.

A simple solution is to pseudo-recursively loop from the "completion callback" of the final step of the animation.

start() {
    var current = 0;
    (function loop() {
        let img = imgList[current++];
        current %= imgList.length;
        let $sel = $(this.settings.selector);
        $sel.fadeOut(this.settings.fadeTime, () => {
            $sel.attr("src",`${this.imgDir}/${img}`);
            $sel.fadeIn(this.settings.fadeTime, loop); // <-- here
        });
    })();
}

请注意,我已经删除了for ... of循环-每次loop函数的传递都只能处理幻灯片的一帧.

Note that I've removed the for ... of loop - each pass of the loop function here just handles one frame of the slideshow.

这将解决原始代码中似乎有错误的问题,在原始代码中,您将获得三个连续的fadeOut动画(其中两个当然是不可见的),因为代码中的任何内容都不允许第一个循环fadeOut, change image, fadeInfor ... of循环的下一次迭代开始之前完成.

This would resolve what appears to be a bug in your original code, where you'd get three consecutive fadeOut animations (two of which would of course be invisible) because nothing in your code allows for the first cycle of fadeOut, change image, fadeIn to complete before the next iteration of the for ... of loop starts.