سؤال

This code is running all 21 console logs all at once. It should, however, run them one at a time at a set interval Any suggestions?

var index = 1;
var switchBG = function(num){
    if( num < 22 ){
        console.log('index' + index);
        console.log('num' + num);
        index++;
        function_timer(index);
    }
};

var timer;
var function_timer = function(index){
    clearTimeout(timer);
    timer = setTimeout(switchBG(index), 10000);

};
هل كانت مفيدة؟

المحلول

You need to pass a function as an argument to setTimeout. Try this:

timer = setTimeout(function() {
    switchBG(index);
}, 10000);

Doing setTimeout(switchBG(index), 10000); basically evaluates switchBG(index) and passes its return value (which is currently undefined) to setTimeout.

نصائح أخرى

When you do:

setTimeout(switchBG(index), 10000);

you are calling switchBG(index) immediately, and then passing it's return value (which is undefined) to setTimeout. Instead you want to pass a function reference, and then pass the additional arguments to setTimeout:

setTimeout(switchBG, 10000, index);

If you want to use additional arguments to setTimeout like that to work in Internet Explorer, you'll need to shim it. It will work in every other browser without a shim.

If you want to support IE and don't want to use the shim, you can create an extra anonymous function to achieve the same result:

setTimeout(function(){ switchBG(index); }, 10000);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top