鍍金池/ 問答/HTML/ 如何在for-in遍歷出對(duì)象,已對(duì)象作為參數(shù)每隔一段時(shí)間執(zhí)行函數(shù)?

如何在for-in遍歷出對(duì)象,已對(duì)象作為參數(shù)每隔一段時(shí)間執(zhí)行函數(shù)?

頁面上有多個(gè)輪播,需要獲取用戶設(shè)置的值來調(diào)整輪播效果,輪播間隔時(shí)間是相同的,需要處理延時(shí)時(shí)間來不同步切換,
想到用定時(shí)器來控制輪播的初始化。
function swiperInit(option,time){

             console.log(option);
                for(var key in option){
                    setTimeout(function(){
                        new Swiper(key, {
                            direction: 'horizontal',
                            loop: true,
                            autoplay: time,
                            speed: 2000,
                            effect: option[key],
                        });
                    },500);
                }
         }

swiperInit(option,advertTime);

回答
編輯回答
做不到

中間這段改成:

for (var key in option) {
    !(function(key) {
            setTimeout(function() {
                    new Swiper(key, {
                        direction: 'horizontal',
                        loop: true,
                        autoplay: time,
                        speed: 2000,
                        effect: option[key],
                    })
                }
            }, 500);
    })(key)
}
2017年4月8日 12:54
編輯回答
瘋子范

感覺就是個(gè)閉包的問題,你試試下面的代碼:

function swiperInit(option,time){
    console.log(option);
    var i = 0
    for(var key in option) {
        setTimeout((function(key){
            return function() {
                new Swiper(key, {
                    direction: 'horizontal',
                    loop: true,
                    autoplay: time,
                    speed: 2000,
                    effect: option[key],
                });
            }
        })(key),500 * i++);
    }
}
swiperInit(option,advertTime);
2017年3月15日 23:54
編輯回答
北城荒

我最近寫的項(xiàng)目跟你也挺類似的,你把定時(shí)器去掉,把a(bǔ)jax換成同步,看看能不能減少你的困難度

2017年8月19日 05:35
編輯回答
心悲涼

閉包問題 在 for里面寫一個(gè)匿名函數(shù)就可以了

for(var currentKey in obj){
    (function (key) {
        setTimeout(function () {
            new Swiper(key, {
                direction: 'horizontal',
                loop: true,
                autoplay: time,
                speed: 2000,
                effect: option[key],
            })
        }, 500);
    })(currentKey);
}
2018年6月11日 06:52