-1

Inside one JS function I call another,.. I want to call it every 30 seconds

function showPopup() {
    $.get("/Feedback.aspx", function (data) {
        if (post_HasError(data))
            return;
        initPopup("popup-common", "feedback", data);
    });
    setInterval(AddFormToSession(3), 30000);
}
function AddFormToSession(form) {
    alert(1);
  var url1 = form == 3 ? "Feedback.aspx/AddFormToSession" : "Request.aspx/AddFormToSession";
    $.ajax
    ({
         type: "POST",
         async: true,
         url: url1,
         data: "{'funcParam':'" + $('#aspnetForm').serialize() + "'}",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function(msg)
         {
             console.log(msg.d);
         }
     });
  }

is called only the first time

user2864740
  • 60,010
  • 15
  • 145
  • 220
Alex
  • 8,908
  • 28
  • 103
  • 157
  • `setInterval(AddFormToSession(3), ..)` - is immediately invoking the callback function and using that as the argument; and yes, this *is* a duplicate – user2864740 Jun 23 '14 at 04:32
  • http://stackoverflow.com/questions/2037203/why-is-my-function-call-that-should-be-scheduled-by-settimeout-executed-immediat , http://stackoverflow.com/questions/15378302/settimeout-does-not-delay , http://stackoverflow.com/questions/4120781/settimeout-ignores-timeout-fires-immediately?lq=1 – user2864740 Jun 23 '14 at 04:33
  • Place outside of function. – byJeevan Jun 23 '14 at 04:37

2 Answers2

4

You do not call a function in first argument of setInterval. Calling function returns the value from that function, not the reference to that function. In your case, it is returning undefined.

You just pass a reference of function. You may use anonymous function and then call from there.

setInterval(function () {
 AddFormToSession(3);
}, 30000);

From comments:

  1. The function object is passed, not a "reference"
  2. A function call as the first argument is fine if it returns a function.
Jashwant
  • 28,410
  • 16
  • 70
  • 105
  • Nit: the function object *is* passed, not a "reference" – user2864740 Jun 23 '14 at 04:45
  • Well, the *value* of the first argument is set to a reference to the function object. A function call as the first argument is fine if it returns a function: `setTimeout(function(){return function(){...}}(), 0)`. :-) – RobG Jun 23 '14 at 04:56
0

setInterval accepts a function name (i.e. AddFormToSession). What you've provided is a return value from a function call.

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159