Search code examples
javascriptjqueryfor-loopsettimeoutcleartimeout

SetTimeout not functioning properly


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);

};

Solution

  • 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.