无限期地重复一个函数,最好不使用setInterval() [英] Repeating a function indefinitely, preferably without using setInterval()

查看:80
本文介绍了无限期地重复一个函数,最好不使用setInterval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个幻灯片框架,无法找出循环动画功能的最佳方法,我知道我可以使用setInterval(),但想知道是否有更好的方法可以重复它而又不会占用大量资源

I am building a slide show framework and was having trouble figuring out the best way to cycle the animation function, I know I could use setInterval() but was wondering if there was a better way to repeat it without being to resource intensive.

JAVASCRIPT:

JAVASCRIPT:

class slideShow {
    constructor(imgDir, dataList) {
        this.imgDir = imgDir;
        this.dataList = dataList;
        this.settings = 0;
        this.imgList = 0;
        this._init();
    }
    _init(){
        $.getJSON(`${this.imgDir}/${this.dataList}.json`, (data)=>{
            this.settings = data.settings;
            this.imgList = data.imgList;
        })
    }
    start(){
        for(let img of this.imgList){
            $(this.settings.selector).fadeOut(this.settings.fadeTime, ()=>{
                $(this.settings.selector).attr("src",`${this.imgDir}/${img}`);
                $(this.settings.selector).fadeIn(this.settings.fadeTime);
            });
        }
    }
}

JSON:

{
    "settings":{
        "selector":"#slideShow",
        "fadeTime":1000
    },
    "imgList":[
        "slide_01.jpg",
        "slide_02.jpg",
        "slide_03.jpg"
    ]
}

推荐答案

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

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.

这篇关于无限期地重复一个函数,最好不使用setInterval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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