Lelio Faieta
Lelio Faieta

Reputation: 6673

SetInterval not repeating the function execution

I have a js structure like this:

var intervalID;

function counterUpdater(){
    intervalID = setInterval(ajax_counter_upload(),10000);  
}
function ajax_counter_upload(){
    $.ajax({
        type: "POST",
        url: "plan/counter.php",
        data: {tipo:'BP'},
        success: function(data){
            $("#spinner_msg").fadeTo(200,0.1,
                function(){
                    $(this).html(data);
                    $(this).fadeTo(900,1);
                });
        }
    });
}
function ajax_submit(){
    var submit_val=$("#stato").serialize();
    dest="plan/new_bp1.php";
    $.ajax({
        type: "POST",
        url: dest,
        data: submit_val,
        success: function(data){ 
            data1=data.split("|");
            if(data1[0]=="Successo"){ 
                $("#spnmsg").fadeTo(200,0.1,
                    function(){$(this).removeClass().addClass("spn_success").html(data1[1]).fadeTo(900,1)});
                }else if(data1[0]=="Errore"){
                    $("#spnmsg").fadeTo(200,0.1,
                    function(){$(this).removeClass().addClass("spn_error").html(data1[1]).fadeTo(900,1)});  
                }
        },
        complete: function(){
            clearInterval(intervalID);
            setTimeout(function(){ $('.container').load('plan/home.php');},2000); 
        }
    });
    setTimeout(function(){counterUpdater();},2000);
}

Goal would be to run counter_updater each 10 seconds when the ajax_submit starts and to stop it when the ajax_submit ends.

What I get now is to run counter_updater only once. What am I doing wrong?

Upvotes: 2

Views: 1330

Answers (1)

Metabolix
Metabolix

Reputation: 186

There's a mistake in your setInterval call: you have parentheses after the (intended) callback function name, which means that the function is actually called once and setInterval gets only the return value (nothing, in this case).

Simply remove the parentheses:

intervalID = setInterval(ajax_counter_upload, 10000);
//                                         ^^

Upvotes: 2

Related Questions